千家信息网

python如何对日期时间进行处理

发表于:2024-09-22 作者:千家信息网编辑
千家信息网最后更新 2024年09月22日,这篇文章给大家分享的是有关python如何对日期时间进行处理的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。开发中常用的日期操作有哪些?获取当前时间获取系统秒数(从纪元时间开
千家信息网最后更新 2024年09月22日python如何对日期时间进行处理

这篇文章给大家分享的是有关python如何对日期时间进行处理的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

开发中常用的日期操作有哪些?

  • 获取当前时间

  • 获取系统秒数(从纪元时间开始)

  • 日期跟秒数之间转换

  • 获取日历等

  • 日期格式化显示输出

这些都非常常见

在python 主要有下面两个模块涵盖了常用日期处理

import timeimport calender

我们看看这两个模块。

time 内置模块

#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2021/11/10 22:49 下午# @Author : LeiXueWei# @CSDN/Juejin/Wechat: 雷学委# @XueWeiTag: CodingDemo# @File : __init__.py.py# @Project : helloimport time# 从19700101 零时刻开始计算经过多少秒,精确到微秒ticks = time.time()print("ticks=", ticks)#获取当前时间print(time.localtime())

运行效果如下:

这个ticks就是从0时刻计算,至今的秒数累计。

可以隔一秒运行这个程序,每次ticks值加上1(近似)

指定输入来构造时间:

#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2021/11/10 22:49 上午# @Author : LeiXueWei# @CSDN/Juejin/Wechat: 雷学委# @XueWeiTag: CodingDemo# @File : createtime.py# @Project : helloimport time#fixed time: time.struct_time(tm_year=2021, tm_mon=11, tm_mday=10, tm_hour=22, tm_min=55, tm_sec=11, tm_wday=16, tm_yday=16, tm_isdst=16)fixed = time.struct_time((2021, 11, 10, 22, 55, 11, 16, 16, 16))print("fixed time:", fixed)

运行效果如下:

calender 内置模块

#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2021/11/10 22:49 上午# @Author : LeiXueWei# @CSDN/Juejin/Wechat: 雷学委# @XueWeiTag: CodingDemo# @File : calendardemo.py# @Project : helloimport calendarcal = calendar.month(2021, 11)print("cal:", cal)

至今输出一个月份,这个在Java的Calendar中也没有。太直接了。

日期格式化处理

这里我们使用了time模块的strftime(str from time):

#第一个参数为格式,第二个参数为时间time.strftime("%Y-%m-%d %H:%M:%S %Z", gmtime))
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2021/11/10 22:49 上午# @Author : LeiXueWei# @CSDN/Juejin/Wechat: 雷学委# @XueWeiTag: CodingDemo# @File : createtime2.py# @Project : helloimport timesec = 3600  # 纪元开始后的一个小时(GMT 19700101凌晨)#gmtime = time.gmtime(sec)print("gmtime:", gmtime)  # GMTprint("type:", type(gmtime))print(time.strftime("%b %d %Y %H:%M:%S", gmtime))print(time.strftime("%Y-%m-%d %H:%M:%S", gmtime))print(time.strftime("%Y-%m-%d %H:%M:%S %Z", gmtime))  # 打印日期加上时区print("*" * 16)localtime = time.localtime(sec)print("localtime:", localtime)  # 本地时间print("type:", type(localtime))print(time.strftime("%b %d %Y %H:%M:%S", localtime))print(time.strftime("%Y-%m-%d %H:%M:%S", localtime))print(time.strftime("%Y-%m-%d %H:%M:%S %Z", localtime))  # 打印日期加上时区# 试试其他格式print(time.strftime("%D", localtime))print(time.strftime("%T", localtime))

稍微解释一下:

%Y-%m-%d %H:%M:%S %Z 对应的是
年份4位数-月份-日期 小时:分钟:秒数 时区信息
%b 则是三个字母英文输出月份,比如Jan/Feb 等。

下面是运行结果:

感谢各位的阅读!关于"python如何对日期时间进行处理"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

0