51

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!

charliesneath
  • 1,917
  • 3
  • 21
  • 36

3 Answers3

97
>>> 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

jmcgrath207
  • 1,317
  • 2
  • 19
  • 31
sberry
  • 128,281
  • 18
  • 138
  • 165
  • 2
    NB, this will give you the localtime, not the UTC timestamp – Willem Jan 22 '15 at 10:55
  • https://stackoverflow.com/a/63988322/603653 shows `.replace(tzinfo=datetime.timezone.utc)` to make it UTC, but comments say that isn't always correct – Lucas Walter Dec 08 '22 at 14:39
  • I recommend using `dt.timestamp()` instead of `time.mktime`, especially if you play with time zones. According to the [doc](https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp), `dt.timestamp()` is roughly equivalent to `(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()` – User9123 Aug 16 '23 at 05:20
5

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

RedBaron
  • 4,717
  • 5
  • 41
  • 65
2

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()
jcollado
  • 39,419
  • 8
  • 102
  • 133