How to convert datetime to integer in python

how can I convert YYYY-MM-DD hh: mm: ss format to integer in python? e.g. 2014-02-12 20:51:14 β†’ to integer.

I know how to convert only hh: mm: ss, but not yyyy-mm-dd hh: mm: ss

def time_to_num(time_str): hh, mm , ss = map(int, time_str.split(':')) return ss + 60*(mm + 60*hh) 
+6
source share
2 answers

It depends on which integer should encode. You can convert the date in a few milliseconds from some previous time. People often do this, attached to 12:00 on January 1, 1970, or 1900, etc., and measure time as an integer number of milliseconds from this point. The datetime module (or others like it) will have functions that will do this for you; just google to convert to milliseconds.

If you want to semantically encode the year, month, and day, one way to do this is to multiply these components by a magnitude of order of magnitude large enough to match them with integers:

2012-06-13 β†’ 20120613 = 10,000 * (2012) + 100 * (6) + 1 * (13)

 def to_integer(dt_time): return 10000*dt_time.year + 100*dt_time.month + dt_time.day 

eg.

 In [1]: import datetime In [2]: %cpaste Pasting code; enter '--' alone on the line to stop or use Ctrl-D. :def to_integer(dt_time): : return 10000*dt_time.year + 100*dt_time.month + dt_time.day : # Or take the appropriate chars from a string date representation. :-- In [3]: to_integer(datetime.date(2012, 6, 13)) Out[3]: 20120613 

If you also need minutes and seconds, just add extra orders to display the numbers.

I met this second method very often on legacy systems, especially systems that retrieve date-based data from legacy SQL databases.

very bad . As a result, you create a lot of hacking codes to align dates, calculate month or day offsets, because they will appear in integer format (for example, resetting a month ago by 1 when you go through December, then increase the year value) and the boiler plate to convert to integer format and back.

If such an agreement does not live in the deep, low-level and thoroughly tested API section that you are working on, so that anyone who ever consumes data can really count on this integer representation and all its auxiliary functions, then you end up with a lot of people rewriting basic date processing procedures all over the place.

As a rule, it is much better to leave the value in the context of the date, for example, datetime.date , as long as it is possible, so that operations on it are expressed in a natural, date-based context, and not alone, the developer will personally crack the integer.

+9
source

I think I have a shortcut for this:

 # Importing datetime. from datetime import datetime # Creating a datetime object so we can test. a = datetime.now() # Converting a to string in the desired format (YYYYMMDD) using strftime # and then to int. a = int(a.strftime('%Y%m%d')) 
0
source

Source: https://habr.com/ru/post/1211934/


All Articles