Python 时间操作

Python时间处理

导入模块

import time
from datetime import datetime, timedelta, date

# 时间拼接显示
localtime = time.localtime()
date_time = "%s-%s-%s" % (localtime.tm_year, localtime.tm_mon, localtime.tm_mday)
print(date_time)

输出:

2022-1-21
<class 'str'>

1. 时间运算 比较

# 获取差值 2天
data_time = timedelta(days=2)

t1 = date(2018, 1, 1)
t2 = t1 + data_time
t3 = t1 - data_time

print(t1)
print(t2)
print(t3)

if t1 > t3:
    print(True)
else:
    print(False)

输出

2018-01-01
2018-01-03
2017-12-30
True

2. 字符串转 时间格式 strptime() str-->时间对象

# 字符串 转 时间
time_str = "2017-12-30"
time_time = datetime.strptime(time_str, "%Y-%m-%d")
print(time_time)

输出

2017-12-30 00:00:00

3. strftime() 时间对象-->str

# 时间转字符串 time_time 接上一步
date_str = datetime.strftime(time_time, "%Y-%m-%d")
print(date_str)

输出

2017-12-30
posted @ 2022-01-21 15:03  叨客厨子  阅读(39)  评论(0编辑  收藏  举报