Python——必学内置模块 Datetime

0 阅读1分钟

日期的查询与设定

import datetime

today = datetime.date.today()
print(today)
# 返回当天的日期

time = datetime.datetime.now()
print(time)
# 返回当天的日期和时间

today = datetime.datetime.today()
print('默认格式     :', today)
print('format(): {:%a %b %d %H:%M:%S %Y}'.format(today))
# 对日期进行格式化
# %a代表周几,%b代表月份,%d代表日期,%H:%M:%S代表时间,%Y代表年份

tt = time.timetuple()
print(tt)
# 将时间按格式拆分成元组
print(tt.tm_year)
# 返回年
print(tt.tm_mon)
# 返回月
print(tt.tm_mday)
# 返回日
print(tt.tm_hour)
# 返回小时
print(tt.tm_min)
# 返回分钟
print(tt.tm_sec)
# 返回秒
print(tt.tm_wday)
# 返回一周中的第几天
print(tt.tm_yday)
# 返回一年中的第几天
print(tt.tm_isdst)
# 返回夏令时,1为是,0为否,-1为未知

tomorrow = datetime.datetime(2028, 6, 3, 15, 30, 0)
print(tomorrow)
# 设定时间

日期间隔的计算

import datetime

print('microseconds:', datetime.timedelta(microseconds=1))
print('milliseconds:', datetime.timedelta(milliseconds=1))
print('seconds     :', datetime.timedelta(seconds=1))
print('minutes     :', datetime.timedelta(minutes=1))
print('hours       :', datetime.timedelta(hours=1))
print('days        :', datetime.timedelta(days=1))
print('weeks       :', datetime.timedelta(weeks=1))
# timedelta 方法可以显示详细的时间戳

today = datetime.date.today()
print('Today    :', today)

one_day = datetime.timedelta(days=1)
print('One day  :', one_day)
# 设定间隔为一天
yesterday = today - one_day
print('Yesterday:', yesterday)

tomorrow = today + one_day
print('Tomorrow :', tomorrow)

print()
print('tomorrow - yesterday:', tomorrow - yesterday)
print('yesterday - tomorrow:', yesterday - tomorrow)
  • Timedelta 同样支持设定小时、秒等间隔

09 内置模块-1784430648649.png

日期和时间的比较

import datetime
print('Times:')
t1 = datetime.time(12, 55, 0)
print('  t1:', t1)
t2 = datetime.time(13, 5, 0)
print('  t2:', t2)
print('  t1 < t2:', t1 < t2)

print()
print('Dates:')
d1 = datetime.date.today()
print('  d1:', d1)
d2 = datetime.date.today() + datetime.timedelta(days=1)
print('  d2:', d2)
print('  d1 > d2:', d1 > d2)