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")