The conversion between timestamp and datetime and UTC time is implemented in Python _python

Source: Internet
Author: User
Tags local time timedelta

Python projects often need to convert time between datetime format and timestamp format, or you need to convert UTC time to local time, this article summarizes the transformation between these time functions, for your reference.

One, DateTime converted to timestamp

def datetime2timestamp (DT, convert_to_utc=false):
  ' Converts a DateTime object to UNIX timestamp in milliseconds. '
  if isinstance (DT, datetime.datetime): If
    CONVERT_TO_UTC: # is converted to UTC time
      dt = dt + Datetime.timedelta ( HOURS=-8) # China default time zone
    timestamp = total_seconds (Dt-epoch) return
    long (timestamp) return
  DT

Second, timestamp converted to datetime

def timestamp2datetime (timestamp, convert_to_local=false):
  ' converts UNIX timestamp to a DateTime object. '
  if Isinstance (timestamp, (int, long, float):
    dt = Datetime.datetime.utcfromtimestamp (timestamp)
    if Convert_to_local: # Convert to local time
      dt = dt + Datetime.timedelta (hours=8) # China default time zone return
    DT return
  timestamp

Iii. timestamp of current UTC time

Def timestamp_utc_now (): Return
  Datetime2timestamp (Datetime.datetime.utcnow ())

Iv. current timestamp of local time

Def timestamp_now (): Return
  Datetime2timestamp (Datetime.datetime.now ())

Five UTC time to local time

# need to install Python-dateutil
# Ubuntu under: sudo apt-get install python-dateutil
# or use pip:sudo pip install Python-dateutil From
dateutil import TZ to
Dateutil.tz import tzlocal from
datetime import datetime #
 
get local time Zo NE name
print datetime.now (tzlocal ()). Tzname ()
 
# UTC Zone
from_zone = Tz.gettz (' UTC ')
# in Zone
To_zone = Tz.gettz (' CST ')
 
UTC = Datetime.utcnow ()
 
# Tell the DateTime object, it ' s in UTC time Zone
   UTC = Utc.replace (tzinfo=from_zone)
 
# Convert time zone Local
= Utc.astimezone (to_zone)
Print Datetime.strftime (Local, "%y-%m-%d%h:%m:%s")

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.