捋一捋操作python日期时间处理(上)

269 阅读2分钟

「这是我参与11月更文挑战的第8天,活动详情查看:2021最后一次更文挑战

正式的Python专栏第32篇,同学站住,别错过这个从0开始的文章!

讲了很多数据容器操作,这篇我们看看时间的处理。

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

  • 获取当前时间
  • 获取系统秒数(从纪元时间开始)
  • 日期跟秒数之间转换
  • 获取日历等
  • 日期格式化显示输出

这些都非常常见

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

import time
import 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 : hello


import time

# 从19700101 零时刻开始计算经过多少秒,精确到微秒
ticks = time.time()
print("ticks=", ticks)

#获取当前时间
print(time.localtime())

运行效果如下:

屏幕快照 2021-11-11 上午12.11.46.png

这个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 : hello


import 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)

运行效果如下:

屏幕快照 2021-11-11 上午12.09.49.png

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 : hello


import calendar

cal = calendar.month(2021, 11)

print("cal:", cal)

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

屏幕快照 2021-11-11 上午12.19.42.png

总结

Python 提供的日期处理都非常简单,但是在创建日期方面使用time模块没有那么方便,需要对应元组下标才行。

对了,喜欢Python的朋友,请关注学委的 Python基础专栏 or Python入门到精通大专栏

持续学习持续开发,我是雷学委!
编程很有趣,关键是把技术搞透彻讲明白。
欢迎关注微信,点赞支持收藏!