导入包
from datetime import datetimeimport timetoday = datetime.today()print(type(today)) # <class 'datetime.datetime'>
日期转字符串:strftime
print(today.strftime("%Y-%m-%d"))
字符串转日期:strptime
print(datetime.strptime("-9-8", "%Y-%m-%d")) # 根据指定的格式将字符串转成日期print(datetime.strptime("/9/8", "%Y/%m/%d"))print(datetime.strptime(".9.8", "%Y.%m.%d"))print(datetime.strptime("9月8日", "%Y年%m月%d日"))print(datetime.strptime('06/07/19', '%x'))print(datetime.strptime('06/07/19', '%d/%m/%y'))print(datetime.strptime('06/07/19', '%m/%d/%y'))print(datetime.strptime('Fri Jun 7 16:30:10 ', '%c'))print(time.strptime('Fri Jun 7 16:30:10 ', '%c'))
整数转时间
print(pd.to_datetime(350, format = "%Y%j")) # 350是表示一年中的第几天print(datetime.strptime(str(98), "%Y%m%d"))
时间转整数
int(train_data["date"][0].strftime('%Y%m%d'))
日期型转成时间戳,方便进行大小比较
print(datetime.strptime("-9-8", "%Y-%m-%d").timestamp())print(datetime.strptime("/9/8", "%Y/%m/%d").timestamp())print(datetime.strptime(".9.8", "%Y.%m.%d").timestamp())print(datetime.strptime("9月8日", "%Y年%m月%d日").timestamp())print(time.mktime(time.strptime("-9-8", "%Y-%m-%d")))
时间戳转为时间字符串
ut = 1559896210d = datetime.fromtimestamp(ut) # -06-07 16:30:10print(d)
类型解析
利用parse可以将任意时间格式改为标准格式.
from dateutil.parser import parseprint(parse('Feb 28,, 3pm'))
输出:
-02-28 15:00:00