Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date/time conversion using time.mktime seems wrong

>>> import time
>>> time.strptime("01-31-2009", "%m-%d-%Y")
(2009, 1, 31, 0, 0, 0, 5, 31, -1)
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233378000.0
>>> 60*60*24 # seconds in a day
86400
>>> 1233378000.0 / 86400
14275.208333333334

time.mktime should return the number of seconds since the epoch. Since I'm giving it a time at midnight and the epoch is at midnight, shouldn't the result be evenly divisible by the number of seconds in a day?

like image 522
Daniel Benamy Avatar asked Oct 30 '25 17:10

Daniel Benamy


1 Answers

Short answer: Because of timezones.

The Epoch is in UTC.

For example, I'm on IST (Irish Standard Time) or UTC+1. time.mktime() is relative to my timezone, so on my system this refers to

>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233360000.0

Because you got the result 1233378000, that would suggest that you're 5 hours behind me

>>> (1233378000 - 1233360000) / (60*60)    
5

Have a look at the time.gmtime() function which works off UTC.

like image 82
Philip Reynolds Avatar answered Nov 01 '25 06:11

Philip Reynolds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!