时间和日期

日期时间

1. 系统时间的获取

from datetime import datetime
dt = datetime.now()
print(type(dt))
print(dt)
print(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.month)

 

输出结果

<class 'datetime.datetime'>
2020-06-04 14:41:09.724932
2020 6 4 14 41 9 6

 

 

2. 逝去的时间

from datetime import datetime
import time
dt = datetime.now()
print(dt)
time.sleep(70)
dt1 = datetime.now()
print(dt1)
escape = dt1 - dt
print(type(escape))
print(escape)
print(type(escape.seconds))
print(escape.seconds)
View Code

 

输出结果

2020-06-04 14:47:33.267251
2020-06-04 14:48:43.267708
<class 'datetime.timedelta'>
0:01:10.000457
<class 'int'>
70

 

 

3. 将逝去的时间变为字符串

# escap_time是整型数据
escap_time =escape.seconds
hours = escap_time / 3600
minutes_curtime = escap_time % 3600
minutes = minutes_curtime / 60
seconds_curtime = minutes_curtime % 60
seconds = seconds_curtime
str_time = "%02d:%02d:%02d" % (hours, minutes, seconds)
print(type(str_time))
print(str_time)

 

输出结果

<class 'str'>
00:01:10

 

 

4. 判断字符串是否为时间字符串

def is_time_valid(str_time):
    valid = False
    res = re.findall("^\d+:[0-5]\d:[0-5]\d$", str_time)
    if not res:
        print("时间字符串不合法")
    else:
        valid = True
        print("时间字符串正确")
    return valid, res


if __name__ == '__main__':
    str1 = "00:01:51"
    str1_valid, str1_value = is_time_valid(str1)
    if str1_valid:
        print(str1_value)

    str2 = "00:02:71"
    str2_valid, str2_value = is_time_valid(str2)
    if str2_valid:
        print(str2_value)
View Code

 

输出结果

时间字符串正确
['00:01:51']
时间字符串不合法

 

 

5. 将时间字符串变为datetime类型

t_str = '2020-08-10 09:30:00'
d = datetime.strptime(t_str, '%Y-%m-%d %H:%M:%S')

 

 

6. 时间差:https://www.cnblogs.com/wind-wang/p/5804454.html

nowtime = datetime.now()
t_str = '2020-08-10 08:00:00'
d = datetime.strptime(t_str, '%Y-%m-%d %H:%M:%S')
dur = nowtime - d
# 区别在于天数显不显示
s1 = dur.seconds
s2 = dur.total_seconds()
print(s1)
print(int(s2))

 

 

输出结果

4701
91101

 

两个函数都是获取秒数,其中一个获取秒数会舍去天数,一个是计算总的秒数差

 

posted @ 2020-06-04 15:03  o云淡风轻o  阅读(308)  评论(0编辑  收藏  举报