Conversion between Timestamp Datetime and UTC times is implemented in Python

  • 2020-05-05 11:28:10
  • OfStack

Many times in the Python project, you need to convert time between Datetime and TimeStamp, or you need to convert UTC time to local time. This article summarizes the conversion functions between these times for your reference.

1. Convert Datetime 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: #  Whether to convert to UTC time 
      dt = dt + datetime.timedelta(hours=-8) #  China default time zone 
    timestamp = total_seconds(dt - EPOCH)
    return long(timestamp)
  return dt

ii. TimeStamp is 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: #  Whether to convert to local time 
      dt = dt + datetime.timedelta(hours=8) #  China default time zone 
    return dt
  return timestamp

3. TimeStamp
at the current UTC time
 


def timestamp_utc_now():
  return datetime2timestamp(datetime.datetime.utcnow())

4. TimeStamp
of the current local time
 


def timestamp_now():
  return datetime2timestamp(datetime.datetime.now())

5, UTC time converted to local time
 


#  You need to install python-dateutil
# Ubuntu Bottom: sudo apt-get install python-dateutil
#  Or use PIP : sudo pip install python-dateutil
from dateutil import tz
from dateutil.tz import tzlocal
from datetime import datetime
 
# get local time zone name
print datetime.now(tzlocal()).tzname()
 
# UTC Zone
from_zone = tz.gettz('UTC')
# China Zone
to_zone = tz.gettz('CST')
 
utc = datetime.utcnow()
 
# Tell the datetime object that 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")


Related articles: