Comparing the 4 most common ways to do this, for accuracy:
Method 1: Manual Calculation
from datetime import datetime
total1 = int(datetimeobj.strftime('%S'))
total1 += int(datetimeobj.strftime('%M')) * 60
total1 += int(datetimeobj.strftime('%H')) * 60 * 60
total1 += (int(datetimeobj.strftime('%j')) - 1) * 60 * 60 * 24
total1 += (int(datetimeobj.strftime('%Y')) - 1970) * 60 * 60 * 24 * 365
print ("Method #1: Manual")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total1)
print ("After: %s" % datetime.fromtimestamp(total1))
Output:
Method #1: Manual
Before: 1970-10-01 12:00:00
Seconds: 23630400
After: 1970-10-01 16:00:00
Accuracy test: FAIL (time zone shift)
Method 2: Time Module
import time
from datetime import datetime
total2 = int(time.mktime(datetimeobj.timetuple()))
print ("Method #2: Time Module")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total2)
print ("After: %s" % datetime.fromtimestamp(total2))
Output:
Method #2: Time Module
Before: 1970-10-01 12:00:00
Seconds: 23616000
After: 1970-10-01 12:00:00
Accuracy test: PASS
Method 3: Calendar Module
import calendar
from datetime import datetime
total3 = calendar.timegm(datetimeobj.timetuple())
print ("Method #3: Calendar Module")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total3)
print ("After: %s" % datetime.fromtimestamp(total3))
Output:
Method #3: Calendar Module
Before: 1970-10-01 12:00:00
Seconds: 23616000
After: 1970-10-01 16:00:00
Accuracy test: FAIL (time zone shift)
Method 4: Datetime Timestamp
from datetime import datetime
total4 = datetimeobj.timestamp()
print ("Method #4: datetime timestamp")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total4)
print ("After: %s" % datetime.fromtimestamp(total4))
Output:
Method #2: Time Module
Before: 1970-10-01 12:00:00
Seconds: 23616000
After: 1970-10-01 12:00:00
Accuracy test: PASS
Conclusion
- All 4 methods convert datetime to epoch (total seconds)
- Both the Manual method and Calendar module method are time zone aware.
- Both datetime.timestamp() and time.mktime() methods are time zone unaware.
- Simplest method: datetime.timestamp()
datetime.date
to UTC timestamp in Python – Piculint(t.timestamp())
– Katlynkatmai