Python-日期和时间

时间:2020-06-10 09:57:04   收藏:0   阅读:51

Python 程序能用很多方式处理日期和时间,转换日期格式是一个常见的功能。

Python 提供了一个 time 和 calendar 模块可以用于格式化日期和时间。

时间间隔是以秒为单位的浮点小数。

每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。

Python 的 time 模块下有很多函数可以转换常见日期格式。如函数time.time()用于获取当前时间戳, 如下实例:

import time

times = time.time()
print(times)

# 1591751980.2599757

时间戳单位最适于做日期运算。但是1970年之前的日期就无法以此表示了。太遥远的日期也不行,UNIX和Windows只支持到2038年。

什么是时间元组?

很多Python函数用一个元组装起来的9组数字处理时间:

技术分享图片

上述也就是struct_time元组。这种结构具有如下属性:

技术分享图片

获取当前时间

从返回浮点数的时间戳方式向时间元组转换,只要将浮点数传递给如localtime之类的函数。

import time

times = time.localtime(time.time())
print(times)

# time.struct_time(tm_year=2020, tm_mon=6, tm_mday=10, tm_hour=9, tm_min=31, tm_sec=11, tm_wday=2, tm_yday=162, tm_isdst=0)

获取格式化的时间

你可以根据需求选取各种格式,但是最简单的获取可读的时间模式的函数是asctime():

import time

times = time.asctime(time.localtime(time.time()))
print(times)

# Wed Jun 10 09:32:42 2020

格式化日期

我们可以使用 time 模块的 strftime 方法来格式化日期:

time.strftime(format[, t])
import time

# 格式化成2020-06-10 09:34:29形式
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

# 格式化成Wed Jun 10 09:34:29 2020形式
print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))

# 将格式字符串转换为时间戳
a = "Wed Jun 10 09:34:29 2020"
print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y")))

# 2020-06-10 09:34:29
# Wed Jun 10 09:34:29 2020
# 1459175064.0

python中时间日期格式化符号:

获取某月日历

Calendar模块有很广泛的方法用来处理年历和月历,例如打印某月的月历:

import calendar

month = calendar.month(2020,6)

print(month)

#     June 2020
# Mo Tu We Th Fr Sa Su
#  1  2  3  4  5  6  7
#  8  9 10 11 12 13 14
# 15 16 17 18 19 20 21
# 22 23 24 25 26 27 28
# 29 30

 

原文:https://www.cnblogs.com/zhuifeng-mayi/p/13083099.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!