首页 > 技术文章 > datetime模块

Mr-shen 2019-11-17 11:14 原文

datetime模块

import datetime

1、获取当前时间

# 获取当前时间年月日
print(datetime.date.today())
# 获取当前时间年月日时分秒
print(datetime.datetime.today())
# 获取当前时间的年
print(datetime.datetime.today().year)
# 获取当前时间周几
# 索引从0开始算周一(0-6)
print(datetime.datetime.today().weekday())
# 查看当前时间(北京时间)
print(datetime.datetime.now())

2、获取日期“间隔”对象

import datetime
# 获取时间间隔对象,默认为0:00:00
print(datetime.timedelta())
# 传入间隔时间,得到7天的间隔对象7 days, 0:00:00
print(datetime.timedelta(days=7))

3、时间、日期的计算

日期时间 = 时间对象 + 或 - 日期时间

时间对象 = 日期时间 + 或 - 日期时间

# 日期时间 = 时间对象 + 或 - 日期时间
# 查看当前时间(北京时间)
data_now = datetime.datetime.now()
# 时间对象,5天时间
res = datetime.timedelta(days=5)
# 5天后的现在时间
data_wl = data_now + res
print(data_wl)
# 时间对象 = 日期时间 + 或 - 日期时间
# 时间对象 = 日期时间 + 或 - 日期时间
# 查看当前时间(北京时间)
data_now = datetime.datetime.now()
# 时间对象,5天时间
res = datetime.timedelta(days=5)
# 5天后的现在时间
data_wl = data_now + res
res = data_wl - data_now
print(res)

推荐阅读