Python datatime module enables conversion between timestamps and local time, UTC time
- How to get Unix timestamp
Dt=datetime.datetime.now () # get local Current time
Dt.timestamp () # get timestamp
Note: The timestamp is the current moment minus the UTC time (1970.1.1) The number of seconds at 0 points is not the same as the time zone in which the current system is located, and the timestamp in any time zone is the same at the same time.
The timestamp is the same regardless of whether the local current time is obtained or the UTC time dt=datetime.datetime.now (TIMEZONE.UTC)is obtained.
- DateTime and UTC datetime by timestamp
- Timestamp turn datetime
Datetime.datetime.fromtimestamp (timestamp) # gets local time, type naive datetime obiect
- Timestamp to UTC datetime
There are two ways to get UTC time, but the datetime object type is different.
Way One:
Datetime.datetime.utcfromtimestamp (timestamp) # type naive datetime object
Way two:
Datetime.datetime.fromtimestamp (TIMESTAMP,TIMEZONE.UTC) # Type aware datetime object.
Type naive DateTime object time period is 1970~2038.
Summarize:
- Timestamp does not have a time zone, do not assume that there are different timestamps in the same zone.
- There are two types of datetime object, and even if the values are displayed, different types of object cannot be directly mathematically operated
Python UTC time, local time, and timestamp conversion