Is time.mktime the timezone in python?

I am trying to understand the nature of the era and its behavior. Below I have tried the same date with 2 different time points with 1 naive datetime

import time
import pytz
from datetime import datetime, timedelta

pst = pytz.timezone('America/Los_Angeles')
t = datetime(year=2015, month=2, day=2)
t = pst.localize(t)
time.mktime(t.timetuple()) 
# outputs 1422864000.0


utc = pytz.utc
k = datetime(year=2015, month=2, day=2)
k = utc.localize(k)
time.mktime(k.timetuple())
# outputs 1422864000.0




o = datetime(year=2015, month=2, day=2)
time.mktime(o.timetuple())
# outputs 1422864000.0

      

They all have the same epoch, but this is surprising since the same date in pst must be offset by 7 hours from utc. Can someone explain this?

thank

+3


source to share


1 answer


time.mktime()

returns the same result because it gets almost (~ isdst

) the same input in all three cases:

time.struct_time(tm_year=2015, tm_mon=2, tm_mday=2, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=33, ..)

      

.timetuple()

does not store utc offset. This is equivalent to a naive object datetime

.

In general, the "era", i.e. "seconds since epoch" is independent of the time zone. This is not local time or utc. Knowing the timestamp, you can get both with datetime.fromtimestamp

and datetime.utcfromtimestamp

accordingly.

If your timezone is different from 'America/Los_Angeles'

(different utc offset), all three time instances are different and therefore all three POSIX timestamps are different:

#!/usr/bin/env python3
from datetime import datetime
import pytz # $ pip install pytz

pacific = pytz.timezone('America/Los_Angeles')
naive  = datetime(2015, 2, 2)
pacific_dt = pacific.localize(naive, is_dst=None)
print(pacific_dt.timestamp())

utc_dt = naive.replace(tzinfo=pytz.utc)
print(utc_dt.timestamp())

print(naive.timestamp()) #NOTE: interpret as local time

      



The last call can be used mktime(naive.timetuple())

internally.

Output

1422864000.0
1422835200.0
1422831600.0

      

Note: all three time stamps are different.

To get the POSIX timestamp for older versions of Python see this answer .

+3


source







All Articles