900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > prthon日期型 字符串 数值 时间戳相互转换

prthon日期型 字符串 数值 时间戳相互转换

时间:2021-11-30 14:34:06

相关推荐

prthon日期型 字符串 数值 时间戳相互转换

导入包

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。