time
# 时间戳
time.time()
# 返回 time.struct_time 元组
time.localtime() # time.struct_time(tm_year=2020, tm_mon=12, tm_mday=29, tm_hour=14, tm_min=38, tm_sec=24, tm_wday=1, tm_yday=364, tm_isdst=0)
# time.struct_time 元组转换为时间戳
time.mktime(struct_time) # 传入一个 struct_time 元组
# 时间字符串---》 time.struct_time 元组
time.strptime('2020-02-02', '%Y-%m-%d')
# struct_time元组---》 时间字符串
time.strftime("%Y-%m-%d") # 2020-12-29 14:44:53
time 转换
# 时间戳 ---》 时间 1452646860 -- 2016-01-13
1. time.strftime("%Y-%m-%d", time.localtime(1452646860))
2. pd.to_datetime(int(time.time()) + 28800, unit='s')
# 时间戳 ---》 时间 1609229819 -- 20201229
time.strftime('%Y%m%d', time.localtime(time.time()))
# 时间字符串 ---》 时间戳 2020-02-02 -- 1580572800
time.mktime(time.strptime('2020-02-02', '%Y-%m-%d'))
# 时间字符串 ---》 时间戳 20200202 -- 1580572800
time.mktime(time.strptime('20200202', '%Y%m%d'))
datetime
# datetime.date类
datetime.date.today() # 2020-12-29 datetime.date 类型
datetime.date(2020, 2, 2) # 2020-02-02 datetime.date 类型
datetime.date.today().timetuple() # time.struct_time 元组
datetime.date.today().isoweekday() # 返回今天星期,星期一是 1
datetime.date.today().isoformat() # 返回时间字符串 2020-12-29
datetime.date.today().strftime('%Y%m%d') # 返回字符串 20201229
# datetime.datetime 类
datetime.datetime.strptime('20200202', '%Y%m%d') # 2020-02-02 <class 'datetime.datetime'> 类型
print(datetime.datetime.now().strftime('%Y%m%d')) # 20201229
datetime 转换
unix时间戳转化为当前时间 datetime.datetime.fromtimestamp(1588834800.0)
把时间转换成unix时间戳 datetime.datetime.strptime(str(context.start_minute), "%Y%m%d%H%M%S").timestamp()
import time
import datetime
import pandas as pd
# 时间字符串转换成时间戳
a1 = "2019-5-10 23:40:00"
# 先转换为时间数组
timeArray = time.strptime(a1, "%Y-%m-%d %H:%M:%S")
timeStamp = int(time.mktime(time.strptime(a1, "%Y-%m-%d %H:%M:%S")))
print(timeStamp) 1557502800
# 字符串转换成时间戳
d = '201703270000'
sss = time.mktime(datetime.datetime.strptime(d, "%Y%m%d%H%M%S").timetuple())
print(sss) 1490544000.0
# 时间戳转换成时间字符串
dd = 1490544000.0
dt = pd.to_datetime(dd, unit='s')
print(dt) 2017-03-26 16:00:00 # 时间是格林尼治时间,与北京时间相差8小时
print(datetime.datetime.strptime('201703302359', "%Y%m%d%H%M")) # 2017-03-30 23:59:00
# 获取前一天的时间
now = datetime.datetime.now() # 2020-06-09 11:26:02.823512
before = (now + datetime.timedelta(days=-1)).strftime('%Y%m%d') + '210000'
print(before) # 20200608210000
time.mktime(datetime.datetime.strptime(before, "%Y%m%d%H%M%S").timetuple())# 1591621200.0
# 转换成df对象
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
# 将 "2019-5-10 23:40:00" 群转成时间戳
df_data_resample.index.map(lambda x: time.mktime(time.strptime(str(x), "%Y-%m-%d %H:%M:%S")))