python时间格式转换与复原

1. datetime.datetime

current_time1 = datetime.datetime.today()
current_time1
# datetime.datetime(2018, 8, 10, 9, 54, 20, 534707)
timestamp = current_time1.timestamp()
current_time1_recover = datetime.datetime.fromtimestamp(timestamp)
current_time1_recover
# datetime.datetime(2018, 8, 10, 9, 54, 20, 534707)
current_time1_recover == current_time1
# True

2. datetime.date

current_time2 = datetime.date.today()
time_structure = datetime.date.timetuple(current_time2) 
timestamp = time.mktime(time_structure)
current_time2_recover = datetime.date.fromtimestamp(timestamp)
current_time2_recover
# datetime.date(2018, 8, 10)
current_time2_recover == current_time2
# True

3. datetime.time

current_time3 = datetime.time(16, 24, 2)
time_structure = [current_time3.hour, current_time3.minute, current_time3.second]
current_time3_recover = datetime.time(time_structure[0], time_structure[1], time_structure[2])
current_time3 == current_time3_recover
# True


或者
current_time3 = datetime.time(16, 24, 2)
tmp = current_time3.strftime('%H:%M:%S')
current_time3_recover = datetime.time(int(tmp[0:2]), int(tmp[3:5]), int(tmp[6:]))
current_time3 == current_time3_recover
# True

4. time.struct_time

current_time4 = time.localtime()
current_time4
# time.struct_time(tm_year=2018, tm_mon=8, tm_mday=10, tm_hour=12, tm_min=52, tm_sec=1, tm_wday=4, tm_yday=222, tm_isdst=0)
timestamp = time.mktime(current_time4)
current_time4_recover = time.localtime(timestamp)
current_time4 == current_time4_recover
# True

5 . pandas._libs.tslibs.timestamps.Timestamp

current_time5 = pd.to_datetime('2017-06-20')
time_string = current_time5.strftime('%Y-%m-%d %H:%M:%S')
current_time5_recover = pd.to_datetime(time_string)
current_time5 == current_time5_recover
# True

你可能感兴趣的:(python时间格式转换与复原)