This article describes how to convert Timestamp, Datetime, and UTC time in Python. The example is mainly for UNIX-like systems such as Ubuntu, for more information about how to convert the time between the Datetime and TimeStamp formats in the Python project, or convert the UTC time to the local time, this article summarizes the conversion functions over the past few 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's default time zone timestamp = total_seconds (dt-EPOCH) return long (timestamp) return dt
II. convert TimeStamp 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 of 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. convert UTC time to local time
# Install python-dateutil # Under Ubuntu: sudo apt-get install python-dateutil # or use PIP: sudo pip install python-dateutilfrom dateutil import tzfrom dateutil. tz import tzlocalfrom datetime import datetime # get local time zone nameprint datetime. now (tzlocal ()). tzname () # UTC Zonefrom_zone = tz. gettz ('utc') # China Zoneto_zone = tz. gettz ('cst ') utc = datetime. utcnow () # Tell the datetime object that it's in UTC time zoneutc = utc. replace (tzinfo = from_zone) # Convert time zonelocal = utc. astimezone (to_zone) print datetime. strftime (local, "% Y-% m-% d % H: % M: % S ")