Is it possible to create a UNIX timestamp in Python (number of seconds) with only day, month and year from a date object? I'm essentially looking for what the timestamp would be at midnight (hour, minute and second would be 0).
Thanks!
Is it possible to create a UNIX timestamp in Python (number of seconds) with only day, month and year from a date object? I'm essentially looking for what the timestamp would be at midnight (hour, minute and second would be 0).
Thanks!
>>> import time
>>> import datetime
>>> dt = datetime.datetime.strptime('2012-02-09', '%Y-%m-%d')
>>> time.mktime(dt.timetuple())
1328774400.0
--OR--
>>> dt = datetime.datetime(year=2012, month=2, day=9)
>>> time.mktime(dt.timetuple())
1328774400.0
For other Time types like Hour and Second go here: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
You can also use datetime.combine()
>>> import datetime
>>> import time
>>> date1 = datetime.date(year=2012,day=02,month=02)
>>> date2 = datetime.datetime.combine(date1,datetime.time())
>>> date2
datetime.datetime(2012, 2, 2, 0, 0)
>>> tstamp = time.mktime(date2.timetuple())
>>> tstamp
1328121000.0
The result depends on local timezone (in this case IST). I hope somebody can point me on how to get GMT result
You could do it by getting the number of seconds between the date and the epoch (1 January 1970):
from datetime import datetime
epoch = datetime(1970, 1, 1)
d = datetime(2012, 2, 10)
print (d - epoch).total_seconds()