图解Python时间和日期time和datetime数据类型转换
Posted 小基基o_O
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图解Python时间和日期time和datetime数据类型转换相关的知识,希望对你有一定的参考价值。
文章目录
前言
Python版本:3.7.4
主要内容:时间数据类型转换
4大数据类型
import time, datetime
_print = lambda x: print('\\033[033m%s\\033[0m' % type(x), x)
_print(time.time()) # 秒数
_print(time.strftime('%Y-%m-%d'))
_print(time.localtime())
_print(datetime.datetime.now())
<class 'float'>
1582599349.6660724
<class 'str'>
2020-02-25
<class 'time.struct_time'>
time.struct_time(tm_year=2020, tm_mon=2, tm_mday=25, tm_hour=10, tm_min=55, tm_sec=49, tm_wday=1, tm_yday=56, tm_isdst=0)
<class 'datetime.datetime'>
2020-02-25 10:55:49.666072
图解
time.struct_time
time.struct_time ⇌ str
import time
t = time.localtime()
print(t)
t = time.strftime('%Y-%m-%d %H:%M:%S', t)
print(t)
t = time.strptime(t, '%Y-%m-%d %H:%M:%S')
print(t)
打印结果
time.struct_time(tm_year=2020, tm_mon=2, tm_mday=25, tm_hour=12, tm_min=31, tm_sec=4, tm_wday=1, tm_yday=56, tm_isdst=0)
2020-02-25 12:31:04
time.struct_time(tm_year=2020, tm_mon=2, tm_mday=25, tm_hour=12, tm_min=31, tm_sec=4, tm_wday=1, tm_yday=56, tm_isdst=-1)
time.struct_time ⇌ float
import time
t = time.time() # 秒数
print(t)
t = time.localtime(t)
print(t)
t = time.mktime(t)
print(t)
打印结果
1582609210.184097
time.struct_time(tm_year=2020, tm_mon=2, tm_mday=25, tm_hour=13, tm_min=40, tm_sec=10, tm_wday=1, tm_yday=56, tm_isdst=0)
1582609210.0
datetime.datetime
datetime.datetime ⇌ str
import datetime
t = datetime.datetime.now()
print(t, type(t))
t = t.strftime('%Y-%m-%d %H:%M:%S')
print(t, type(t))
t = datetime.datetime.strptime(t, '%Y-%m-%d %H:%M:%S')
print(t, type(t))
打印结果
2020-02-25 14:13:55.824529 <class 'datetime.datetime'>
2020-02-25 14:13:55 <class 'str'>
2020-02-25 14:13:55 <class 'datetime.datetime'>
datetime.datetime ⇌ float
import datetime
_print = lambda x: print('\\033[033m%s\\033[0m' % type(x), x)
t = datetime.datetime.now()
_print(t)
t = t.timestamp() # 秒数
_print(t)
t = datetime.datetime.fromtimestamp(t)
_print(t)
打印结果
<class 'datetime.datetime'> 2020-02-26 23:28:08.531932
<class 'float'> 1582730888.531932
<class 'datetime.datetime'> 2020-02-26 23:28:08.531932
datetime.datetime ⇌ time.struct_time
import datetime, time
_print = lambda x: print('\\033[033m%s\\033[0m' % type(x), x)
t = datetime.datetime.now()
_print(t)
t = t.timetuple()
_print(t)
t = datetime.datetime(*t[:6])
_print(t)
打印结果
<class 'datetime.datetime'> 2020-02-26 23:43:48.377120
<class 'time.struct_time'> time.struct_time(tm_year=2020, tm_mon=2, tm_mday=26, tm_hour=23, tm_min=43, tm_sec=48, tm_wday=2, tm_yday=57, tm_isdst=-1)
<class 'datetime.datetime'> 2020-02-26 23:43:48
Appendix
en | cn |
---|---|
struct | 结构 |
stamp | 邮票;印记 |
timestamp | n. 时间戳 |
DST(daylight saving time) | 夏令时 |
以上是关于图解Python时间和日期time和datetime数据类型转换的主要内容,如果未能解决你的问题,请参考以下文章
python datetime和time的一些疑惑解答 及 获取上年同期上月等日期
Python之日期与时间处理模块(date和datetime)
Python之日期与时间处理模块(date和datetime)