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.mktimeshould return the number of seconds from an era. Since I give him time at midnight, and the era at midnight, should the result be evenly divisible by the number of seconds per day?

+3
source share
4 answers

Short answer: due to time zones.

The era is in UTC.

For example, I am in IST (Irish Standard Time) or UTC + 1. time.mktime()relative to my time zone, so on my system this applies to

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

Since you received a result of 1233378000, this will mean that you are 5 hours behind me

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

Look at the function time.gmtime()that works with UTC.

+7
source
mktime(...)
    mktime(tuple) -> floating point number

    Convert a time tuple in local time to seconds since the Epoch.

... , .

:

The other representation is a tuple of 9 integers giving local time.
The tuple items are:
  year (four digits, e.g. 1998)
  month (1-12)
  day (1-31)
  hours (0-23)
  minutes (0-59)
  seconds (0-59)
  weekday (0-6, Monday is 0)
  Julian day (day in the year, 1-366)
  DST (Daylight Savings Time) flag (-1, 0 or 1)
If the DST flag is 0, the time is given in the regular time zone;
if it is 1, the time is given in the DST time zone;
if it is -1, mktime() should guess based on the date and time.

, , , 6 :

>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233356400.0
>>> (1233378000.0 - 1233356400)/(60*60)
6.0
+3

, . UTC, , UTC.

>>> calendar.timegm((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233360000
>>> 1233360000 / (60*60*24)
14275

- UTC, , .

, "--", .

+2

. , :

>>> now = time.mktime((2008, 8, 22, 11 ,17, -1, -1, -1, -1))
>>> tomorrow = time.mktime((2008, 8, 23, 11 ,17, -1, -1, -1, -1))
>>> tomorrow - now
86400.0

. ? , . , - . , - , , ...

0
source

Source: https://habr.com/ru/post/1696491/


All Articles