The method to generate Epoch in Python
- 2020-05-30 20:32:51
- OfStack
In Python2, there is no timestamp method for datetime objects, so it is not easy to generate epoch. It is easy to cause errors if the existing method is not handled. For Epoch, see time zone and Epoch
Epoch is generated in 0 Python
from datetime import datetime
# python3
datetime.now().timestamp()
# python2
import time
time.mktime(datetime.now().timetuple()) # In order to compatible python2 and 3 , which is more widely used
1 error code
from datetime import datetime
import pytz
aware_date = datetime.utcnow().replace(tzinfo=pytz.utc)
time.mktime(aware_date.timetuple()) # bug here
2 reasons
The datetime objects in Python are divided into two types: objects with and without time zone information, naive and aware objects. When dealing with naive, all 1 cuts are default to the system time zone without any problem.
When timestamp is executed in Python3, the naive object is treated in the default time zone (time.mktime is called), while the aware object is calculated in seconds with the UTC base time zone, that is, the time zone information is taken into account.
The timetuple methods in Python2 and 3 return no time zone information and no time zone conversion. Calling timetuple for the aware date object, the time zone information is discarded, so calling time.mktime again will get an error result
3 solutions
1. Method 1: convert the aware date of other time zone into the aware object of the default time zone of the current system. As it corresponds to system time zone 1, the aware object performs timetuple like the naive object of no time zone.
Convert time zone see timezone, that is, call the astimezone method with the converted time zone (tzinfo instance)
Since the various time zone instances of tzinfo(abstract base class) are missing from Python2, you need to construct your own time zone object.
Time zone instances can refer to the official documentation implementation of datetime or use the recommended third party library pytz
2. Method 2: calculate the time difference
_EPOCH = datetime(1970, 1, 1, tzinfo=pytz.utc) # The first 3 Party libraries pytz
(aware_date - _EPOCH).total_seconds()