Python中日期时间相关

目录

一、datetime

1、date

2、time

3、datetime

4、timedelta

二、time

三、calendar

一、datetime

首先要导入该模块

from datetime import date, time, datetime, timedelta

1、date

  • 获取今天的日期,可以看到其类型是datetime中的date类型
# 获取今天的日期
date0 = date.today()
print(date0)
# 使用数字构造日期
date0 = date(year=2023, month=5, day=11)
print(date0)
print(type(date0))
# 取得日期中每一部分
print(date0.year, date0.month, date0.day)

  • 格式化字符串
date0 = date.today()

# %y 两位年  %m 两位月  %d 两位日  %Y 四位年
print(date0.strftime("%y/%m/%d"))
print(date0.strftime("%Y/%m/%d"))

2、time

# 可以指定时间
time0 = time(hour=17, minute=15, second=30)
# 获取时间类型
print(type(time0))
# 分别打印 时 分 秒
print(time0.hour, time0.minute, time0.second)
# 格式化为17:15:30形式
print(time0.strftime("%H:%M:%S"))

3、datetime

# 指定 年 月 日 时 分 秒
datetime0 = datetime(year=2001, month=5, day=25, hour=5, minute=29, second=11)
# 获取datetime0类型
print(type(datetime0))
# 分别打印年 月 日 时 分 秒
print(datetime0.year, datetime0.month, datetime0.day, datetime0.hour, datetime0.minute, datetime0.second)
# 格式化
print(datetime0.strftime("%Y-%m-%d %H:%M:%S"))
# 获取现在时间
datetime0 = datetime.now()

4、timedelta


# 现在时间
now = datetime.now()
# 格式化
print(now.strftime("%Y/%m/%d %H:%M:%S"))

# 时间增量
timedelta0 = timedelta(seconds=(14*24*60*60+30))
print(timedelta0.days, timedelta0.seconds)

# 比现在多两周
future = now + timedelta(weeks=2)
print(type(future))
print(future, future.strftime("%Y/%m/%d %H:%M:%S"))

# 比现在少一天零30分钟
ago = now - timedelta(days=1, minutes= 50)
print(ago, ago.strftime("%Y/%m/%d %H:%M:%S"))

二、time

time为Python内置时间模块

导入语句如下:

import time
  •  程序阻塞,休眠、等待一定秒数
print(time)
print(1)
# 暂停5秒
time.sleep(5)
print(2)
time.sleep(5)
print(3)

  •  获取当前时间戳,自1970-1-1开始
# time.time整数部分是1970-1-1 0时到现在的秒数
print(time.time())
time.sleep(5)
print(time.time())

  • 获取本地时间结构体
print(time.strftime("%Y/%m/%d %H:%M:%S", (1999, 9, 9, 9, 9, 9, 0, 0, 0,)))
print(time.ctime())
# 获取时间结构体
print(time.localtime())

  • 将时间格式化
print(time.strftime("%Y/%m/%d %H:%M:%S", time.localtime()))

三、calendar

导入语句如下:

import calendar
  • 获取年历:写入年数
# 年历
print(calendar.calendar(2024))

  • 获取月历:写入是某年的几月
# 月历
print(calendar.month(2024, 1))

  • 获取某日是周几:写入某年某月的第几天
# 周几
print(calendar.weekday(2024, 1, 11))

显示为3,因为从0到6

  • 查看是否是闰年:写入年数
# 是否是闰年
print(calendar.isleap(2024))
print(calendar.isleap(2021))
print(calendar.isleap(2000))
print(calendar.isleap(1985))

  • 18
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

火爆辣椒abc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值