Convert string date to timestamp in Python
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.