【Python】datetime函数用法

datetime.date 表示日期的类 日期对象

复制代码
    print("日期的类:", datetime.date(2023, 11, 21))
    print("当天的年月日:", datetime.date.today())
    print("当天的年:", datetime.date.today().year)
    print("当天的月:", datetime.date.today().month)
    print("当天的日:", datetime.date.today().day)
    print("让所使用的日期符合ISO标准 (年份,周数,星期数):", datetime.date.today().isocalendar())
    print("返回符合ISO 8601标准 (YYYY-MM-DD) 的日期字符串:", datetime.date.today().isoformat())
    print("返回符合ISO标准的指定日期所在的星期数(周一为1…周日为7):", datetime.date.today().isoweekday())
    print("把日期时间按照给定的format进行格式化:", datetime.date.today().strftime("%Y/%m/%d"))
    print("返回英文的时间格式标准:", datetime.date.today().ctime())
复制代码

 

执行结果

 

 

datetime.time 表示时间的类 时间对象

复制代码
    a = datetime.time(23, 59, 59, 823)
    print("time类由hour小时、minute分钟、second秒、microsecond毫秒和tzinfo五部分组成", a)
    print("hour小时", a.hour)
    print("minute分钟", a.minute)
    print("second秒", a.second)
    print("microsecond毫秒", a.microsecond)
    print("用于给定的参数替换:", a.replace(hour=21))
    print("新时间区信息:", datetime.time().tzname())
    print("返回时区的时间偏移量:", datetime.time().utcoffset())
复制代码

 

 执行结果

 

 

datetime.datetime() 表示日期时间的类 日期时间对象

复制代码
    print("返回当前系统时间:", datetime.datetime.now())
    print("datetime.datetime类型转化成str类型:", datetime.datetime.now().ctime())
    print("返回当前日期时间的日期部分:", datetime.datetime.now().date())
    print("返回当前日期时间的时间部分:", datetime.datetime.now().time())
    print("返回当前日期时间的日部分:", datetime.datetime.now().day)
    print("返回UTC时间元组:", datetime.datetime.now().utctimetuple())
    print("将一个date对象和一个time对象合并生成一个datetime对象:", datetime.datetime.combine(datetime.datetime.now().date(), datetime.datetime.now().time()))
    print("由日期格式转化为字符串格式:", datetime.datetime.now().strftime('%b-%d-%Y %H:%M:%S'))
    print("由字符串格式转化为日期格式:", datetime.datetime.strptime(datetime.datetime.now().strftime('%b-%d-%Y %H:%M:%S'), '%b-%d-%Y %H:%M:%S'))
复制代码

 

 执行结果

 

 

 

datetime.timedelta 表示时间间隔 即两个时间点的间隔

    delta = datetime.timedelta(days=2, hours=2)
    print("当前时间:", datetime.datetime.now())
    print("求出距离当前时间向前2天2小时的时间:", datetime.datetime.now() - delta)

 

 执行结果

 

获取固定日期的前一天日期

import datetime
# 格式化当天日期
todate = datetime.datetime.strptime(v_sysdate, "%Y%m%d")
# 设置需要减去的天数,如上一天-1
yesdate = todate - datetime.timedelta(days=1)
print(yesdate.strftime("%Y%m%d"))

 

 执行结果:

 

 

 

 

 

拓展

datetime.strftime()  可用格式化符号

 

posted @   Phoenixy  阅读(1310)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
历史上的今天:
2022-03-21 【测试工具】测试中常用工具
点击右上角即可分享
微信分享提示