In our daily work, we often encounter python Time format conversion problem , For example, time stamp is converted to formatted time 、 Convert formatted time to timestamp , Here's a summary .
Before concluding, we need to clarify a key point : The time zone
The time zone : The time zones we usually use are generally divided into UTC
Time and UTC+8 ( Dongba )
Time , Dongba CT — China standard time Simply understood as Chinese time ,UTC WET — Western European time zone ,GMT - Greenwich mean time , It is simply understood as British time . Dongba time ratio UTC Time is almost eight hours .
World time zone map
import time
import pytz
import datetime
# return Dongba Time stamp
def get_shanghai_timestamp(date_time):
time_zone = pytz.timezone('Asia/Shanghai')
timeArray = datetime.datetime.strptime(date_time, "%Y-%m-%d %H:%M:%S")
local_dt = timeArray.astimezone(time_zone)
print('>>>', int(time.mktime(local_dt.timetuple())))
get_timestamp('2018-07-13 16:00:00')
import time
import pytz
import datetime
# return utc Time stamp
def get_utc_timestamp(utc_time_str, utc_format=r'%Y-%m-%d %H:%M:%S'):
local_tz = pytz.timezone('UTC') # Define the local time zone ( Dongba time ratio utc Fast time 8 Hours )
utc_dt = datetime.datetime.strptime(utc_time_str, utc_format) # Convert the format of world time into datetime.datetime Format
local_dt = utc_dt.astimezone(local_tz) # I want to datetime Add the world time zone to the format , then astimezone Switch time zone : World time zone ==> Local time zone
return int(time.mktime(local_dt.timetuple())) # Return local timestamp
print(get_utc_timestamp('2018-07-13 16:00:00', utc_format='%Y-%m-%d %H:%M:%S'))
# Mode one :
import time
import pytz
import datetime
def get_local_format_time(timestamp):
local_time=time.localtime()
format_time=time.strftime("%Y-%m-%d %H:%M:%S", local_time)
return format_time
get_local_format_time(1529112900)
# Mode two :
def local_to_utc(local_ts, time_format=r'%Y-%m-%d %H:%M:%S'):
time_zone = pytz.timezone('Asia/Shanghai')
time_str = time.strftime(time_format, time.localtime(local_ts)) # First, convert the local timestamp into a time tuple , use strftime Format as a string
dt = datetime.datetime.strptime(time_str, time_format) # Use string strptime Convert to datetime in datetime Format
utc_dt = dt.astimezone(time_zone) # astimezone Switch to a utc The time zone
return utc_dt.strftime(time_format) # return utc Format time
get_local_format_time(1529112900)
def get_utc_format_time(local_ts, time_format=r'%Y-%m-%d %H:%M:%S'):
time_str = time.strftime(time_format, time.localtime(local_ts)) # First, convert the local timestamp into a time tuple , use strftime Format as a string
dt = datetime.datetime.strptime(time_str, time_format) # Use string strptime Convert to datetime in datetime Format
utc_dt = dt.astimezone(pytz.utc) # astimezone Switch to a utc The time zone
return utc_dt.strftime(time_format) # return utc Format time
get_utc_format_time(1529112900)