57

How can I convert YYYY-MM-DD hh:mm:ss format to integer in python? for example 2014-02-12 20:51:14 -> to integer.

I only know how to convert 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)
Tomáš Konyárik
  • 593
  • 1
  • 4
  • 7
  • Please be wary about case sensitivity. `y` for example [is not the same as `Y`](https://www.w3schools.com/python/gloss_python_date_format_codes.asp). – i_want_more_edits Jan 12 '22 at 12:23

7 Answers7

55

It depends on what the integer is supposed to encode. You could convert the date to a number of milliseconds from some previous time. People often do this affixed to 12:00 am January 1 1970, or 1900, etc., and measure time as an integer number of milliseconds from that point. The datetime module (or others like it) will have functions that do this for you: for example, you can use int(datetime.datetime.utcnow().timestamp()).

If you want to semantically encode the year, month, and day, one way to do it is to multiply those components by order-of-magnitude values large enough to juxtapose them within the integer digits:

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

E.g.

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 want minutes and seconds, then just include further orders of magnitude as needed to display the digits.

I've encountered this second method very often in legacy systems, especially systems that pull date-based data out of legacy SQL databases.

It is very bad. You end up writing a lot of hacky code for aligning dates, computing month or day offsets as they would appear in the integer format (e.g. resetting the month back to 1 as you pass December, then incrementing the year value), and boiler plate for converting to and from the integer format all over.

Unless such a convention lives in a deep, low-level, and thoroughly tested section of the API you're working on, such that everyone who ever consumes the data really can count on this integer representation and all of its helper functions, then you end up with lots of people re-writing basic date-handling routines all over the place.

It's generally much better to leave the value in a date context, like datetime.date, for as long as you possibly can, so that the operations upon it are expressed in a natural, date-based context, and not some lone developer's personal hack into an integer.

Rich Smith
  • 1,675
  • 12
  • 24
ely
  • 74,674
  • 34
  • 147
  • 228
  • 1
    oh!, datetime.datetime.now().timestamp() is a float, i expected a string (i'm surprised that there is enough precision for this to be the default behavior, neat!) – ThorSummoner Nov 01 '20 at 01:11
25

I think I have a shortcut for that:

# 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'))
Chicrala
  • 994
  • 12
  • 23
  • 1
    does this method take into account your timezone? I believe it does. how to do it universal? – Akronix Apr 14 '19 at 16:19
  • I believe you can get this as demonstrated [here](https://stackoverflow.com/questions/4530069/python-how-to-get-a-value-of-datetime-today-that-is-timezone-aware) where they use **pytz** library to get the timezone you may need. – Chicrala Apr 15 '19 at 11:52
  • 2
    Not sure what you meant by "take into account your timzone" but datetime.now() returns the local datetime. You can use datetime.utcnow() if you want the utc datetime. – Romain Vincent Feb 12 '20 at 09:32
9

This in an example that can be used for example to feed a database key, I sometimes use instead of using AUTOINCREMENT options.

import datetime 

dt = datetime.datetime.now()
seq = int(dt.strftime("%Y%m%d%H%M%S"))
6

The other answers focused on a human-readable representation with int(mydate.strftime("%Y%m%d%H%M%S")). But this makes you lose a lot, including normal integer semantics and arithmetics, therefore I would prefer something like bash date's "seconds since the epoch (1970-01-01 UTC)".

As a reference, you could use the following bash command to get 1392234674 as a result:

date +%s --date="2014-02-12 20:51:14"

As ely hinted in the accepted answer, just a plain number representation is unmistakeable and by far easier to handle and parse, especially programmatically. Plus conversion from and to human-readable is an easy oneliner both ways.


To do the same thing in python, you can use datetime.timestamp() as djvg commented. For other methods you can consider the edit history.

Cadoiz
  • 1,446
  • 21
  • 31
4

Here is a simple date -> second conversion tool:

def time_to_int(dateobj):
    total = int(dateobj.strftime('%S'))
    total += int(dateobj.strftime('%M')) * 60
    total += int(dateobj.strftime('%H')) * 60 * 60
    total += (int(dateobj.strftime('%j')) - 1) * 60 * 60 * 24
    total += (int(dateobj.strftime('%Y')) - 1970) * 60 * 60 * 24 * 365
    return total

(Effectively a UNIX timestamp calculator)

Example use:

from datetime import datetime
x = datetime(1970, 1, 1)
time_to_int(x)

Output: 0

x = datetime(2021, 12, 31)
time_to_int(x)

Output: 1639785600

x = datetime(2022, 1, 1)
time_to_int(x)

Output: 1639872000

x = datetime(2022, 1, 2)
time_to_int(x)

Output: 1639958400

leenremm
  • 1,083
  • 13
  • 19
2

When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like "2018-11-03" must be like 20181103 in int for that you have to 2018*10000 + 100* 11 + 3

Similarly another example, "2018-11-03 10:02:05" must be like 20181103100205 in int

Explanatory Code

dt = datetime(2018,11,3,10,2,5)
print (dt)

#print (dt.timestamp()) # unix representation ... not useful when converting to int

print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100  + dt.day)
print (int(dt.strftime("%Y%m%d")))

print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000  +  dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))

General Function

To avoid that doing manually use below function

def datetime_to_int(dt):
    return int(dt.strftime("%Y%m%d%H%M%S"))
Atta Jutt
  • 452
  • 5
  • 7
1
df.Date = df.Date.str.replace('-', '').astype(int)
Vega
  • 27,856
  • 27
  • 95
  • 103