Convert string date to timestamp in Python Convert string date to timestamp in Python python python

Convert string date to timestamp in Python


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


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.


To convert the string into a date object:

from datetime import date, datetimedate_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 calendartimestamp1 = calendar.timegm(utc_date.timetuple())timestamp2 = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * 24*60*60assert timestamp1 == timestamp2
  • date object represents midnight in local time

    import timetimestamp3 = 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.


matomo