strftime和strptime
strftime()函数是用来格式化一个日期、日期时间和时间的函数,支持date、datetime、time等类,把这些日期、日期时间或时间通过格式字符要求格式为字符串表示。相反strptime()函数就是从字符串表示的日期时间按格式化字符串要求转换为相应的日期时间。
以1970年1月1日开始的秒的处理
import time
timeofseconds = 1528387200
time.localtime(timeofseconds)
# time.struct_time(tm_year=2018, tm_mon=6, tm_mday=8, tm_hour=0, tm_min=0,
# tm_sec=0, tm_wday=4, tm_yday=159, tm_isdst=0)
formatedday = time.strftime("%Y%m%d", time.localtime(timeofseconds))
# formatedday: '20180608'
以字符串年月日时分秒形式构成的时间的转换
import time
timeofstring = '2018-01-01 09:00:00'
time.strptime(timeofstring, '%Y-%m-%d %H:%M:%S')
# time.struct_time(tm_year=2018, tm_mon=1, tm_mday=1, tm_hour=9, tm_min=0,
# tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)
timeofseconds = int(time.mktime(time.strptime(timeofstring, '%Y-%m-%d %H:%M:%S')))
# timeofseconds: 1514768400
将int的时间戳转换成Timestamp
import pandas as pd
timeofseconds = 1527868800
pd.Timestamp(timeofseconds , unit='s')
# Timestamp('2018-06-01 16:00:00')
pd.Timestamp(timeofseconds , unit='s', tz='Asia/Shanghai')
# Timestamp('2018-06-02 00:00:00+0800', tz='Asia/Shanghai')
# tz in China: Asia/Shanghai or Asia/Chongqing
使用to_datetime也可以处理时间戳,但如果原始的时间戳是UTC+8的,那么处理要麻烦点,需要先添加UTC时区信息,再转换成我们的时区
pd.to_datetime(timeofseconds, unit='s')
# Timestamp('2018-06-01 16:00:00')
pd.to_datetime(timeofseconds, unit='s').tz_localize('UTC').tz_convert('Asia/Chongqing')
# Timestamp('2018-06-02 00:00:00+0800', tz='Asia/Chongqing')
更详细的可以参考官方文档: