Python中的时间日期函数详解
Python语言中,时间日期函数是常用的一种函数。时间和日期在计算机应用中广泛应用,所以在Python中有很多与时间和日期有关的函数。本文将简单介绍一些常用的时间日期函数。
1. time模块
time模块是Python中处理日期和时间的标准库,它提供了时间获取、时间转换、时间运算等方面的功能。常用函数如下:
1.1 time()
time()函数返回从1970年1月1日午夜到当前时间的秒数。该函数不接受任何参数。
示例代码:
import time
print("当前时间戳为:", time.time())
输出结果:
当前时间戳为:1610057286.7859783
1.2 ctime()
ctime()函数将时间戳转换成一个字符串格式的时间。
示例代码:
import time
timestamp = time.time()
print(time.ctime(timestamp))
输出结果:
Thu Jan 7 14:34:46 2021
1.3 localtime()
localtime()函数将时间戳转换成本地时间,返回的是一个表示本地时间的struct_time对象。
示例代码:
import time
timestamp = time.time()
localtime = time.localtime(timestamp)
print(localtime)
输出结果:
time.struct_time(tm_year=2021, tm_mon=1, tm_mday=7, tm_hour=14, tm_min=38, tm_sec=19, tm_wday=3, tm_yday=7, tm_isdst=0)
1.4 strptime()
strptime()函数将一个字符串解析成时间元组。它有两个参数:一个是字符串,一个是日期格式。日期格式中需要用到一些符号来代表不同信息,例如%Y表示四位数的年份,%m表示月份。
示例代码:
import time
str_time = "2021-01-07 14:41:00"
format = "%Y-%m-%d %H:%M:%S"
time_tuple = time.strptime(str_time, format)
print(time_tuple)
输出结果:
time.struct_time(tm_year=2021, tm_mon=1, tm_mday=7, tm_hour=14, tm_min=41, tm_sec=0, tm_wday=3, tm_yday=7, tm_isdst=-1)
2. datetime模块
datetime模块提供了处理日期和时间的方式,它比time模块更加高级,更加灵活。常用函数如下:
2.1 datetime.now()
now()方法获取当前日期和时间,返回的是一个datetime对象。
示例代码:
import datetime
now = datetime.datetime.now()
print(now)
输出结果:
2021-01-07 14:50:57.215010
2.2 datetime.strftime()
strftime()方法将时间格式化成字符串。需要一个格式化字符串作为参数,可以用来自定义代表日期和时间的字符串。
示例代码:
import datetime
now = datetime.datetime.now()
str_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(str_date)
输出结果:
2021-01-07 14:53:19
2.3 datetime.strptime()
strptime()函数可以将一个字符串转化为日期和时间。
示例代码:
import datetime
str_date = "2021-01-07 14:55:00"
format = "%Y-%m-%d %H:%M:%S"
date_time = datetime.datetime.strptime(str_date, format)
print(date_time)
输出结果:
2021-01-07 14:55:00
3. calendar模块
calendar模块提供了处理日历的功能,包括打印日历和返回月份的日历文本等。常用函数如下:
3.1 calendar.month()
month()函数可以打印出指定年月的日历。接受两个参数,一个是年份,一个是月份。
示例代码:
import calendar
cal = calendar.month(2021, 1)
print(cal)
输出结果:
January 2021
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 31
3.2 calendar.isleap()
isleap()函数判断指定年份是否为闰年,如果是返回True,否则返回False。
示例代码:
import calendar
print(calendar.isleap(2021))
print(calendar.isleap(2020))
输出结果:
False
True
总结
以上就是Python中常用的一些时间日期函数,还有一些其他函数可以根据实际需要去探索。时间日期在Python应用中有着非常重要的作用,透彻理解时间日期模块的设计和用法,对于Python程序员来说是非常重要的。
