Python UTC time, local time, and timestamp conversion

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.