Python timestamps and time strings convert instance code to each other

  • 2020-04-02 13:15:33
  • OfStack


# set a As a string 
import time
a = "2011-09-28 10:00:00"
# Intermediate procedures, usually need to convert the string into a time array 
time.strptime(a,'%Y-%m-%d %H:%M:%S')
>>time.struct_time(tm_year=2011, tm_mon=9, tm_mday=27, tm_hour=10, tm_min=50, tm_sec=0, tm_wday=1, tm_yday=270, tm_isdst=-1)
# will "2011-09-28 10:00:00" Convert to a timestamp 
time.mktime(time.strptime(a,'%Y-%m-%d %H:%M:%S'))
>>1317091800.0
# Converts the timestamp to localtime
x = time.localtime(1317091800.0)
time.strftime('%Y-%m-%d %H:%M:%S',x)
>>2011-09-27 10:50:00


Related articles: