The Python Oracle

Convert string date to timestamp in Python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Industries in Orbit Looping

--

Chapters
00:00 Question
00:20 Accepted answer (Score 429)
00:32 Answer 2 (Score 77)
00:52 Answer 3 (Score 45)
01:03 Answer 4 (Score 44)
01:30 Thank you

--

Full question
https://stackoverflow.com/questions/9637...

Answer 1 links:
[here]: https://pypi.python.org/pypi/ciso8601

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #datetime

#avk47



ACCEPTED ANSWER

Score 445


>>> import time
>>> import datetime
>>> s = "01/12/2011"
>>> time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
1322697600.0



ANSWER 2

Score 83


I use ciso8601, which is 62x faster than datetime's strptime.

t = "01/12/2011"
ts = ciso8601.parse_datetime(t)
# to get time in seconds:
time.mktime(ts.timetuple())

You can learn more here.




ANSWER 3

Score 49


>>> int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime("%s"))
1322683200



ANSWER 4

Score 46


To convert the string into a date object:

from datetime import date, datetime

date_string = "01/12/2011"
date_object = date(*map(int, reversed(date_string.split("/"))))
assert date_object == datetime.strptime(date_string, "%d/%m/%Y").date()

The way to convert the date object into POSIX timestamp depends on timezone. From Converting datetime.date to UTC timestamp in Python:

  • date object represents midnight in UTC

    import calendar
    
    timestamp1 = calendar.timegm(utc_date.timetuple())
    timestamp2 = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * 24*60*60
    assert timestamp1 == timestamp2
    
  • date object represents midnight in local time

    import time
    
    timestamp3 = time.mktime(local_date.timetuple())
    assert timestamp3 != timestamp1 or (time.gmtime() == time.localtime())
    

The timestamps are different unless midnight in UTC and in local time is the same time instance.