Python时间日期函数:如何获取、转换和格式化时间日期
Python 中的时间日期函数为我们提供了一系列的操作,包括获取当前时间、格式化输出时间日期、转换时间格式、计算时间差等。本文将围绕 Python 中的时间日期函数进行介绍。
1.获取当前时间
Python 的 time 模块提供了获取当前时间的函数 time() 和 ctime()。其中,time() 函数返回自 Unix Epoch(1970年1月1日)开始的秒数,而 ctime() 函数则返回字符串格式的当前时间。
代码示例:
import time
# 获取当前时间
now1 = time.time()
now2 = time.ctime()
# 输出结果
print("当前时间戳为:", now1)
print("当前时间为:", now2)
输出结果:
当前时间戳为: 1600070788.36868 当前时间为: Fri Sep 11 14:13:08 2020
2.转换时间格式
Python 中的时间格式有很多种,在不同的应用场景下,可能需要转换成不同的格式。Python 中提供了 strftime() 函数用于将时间格式转换为指定的格式。
代码示例:
import time
# 获取当前时间
now = time.localtime()
# 将时间格式化输出
print("现在的时间为:", time.strftime("%Y-%m-%d %H:%M:%S", now))
输出结果:
现在的时间为: 2020-09-11 14:23:43
在 strftime() 函数中,%Y、%m、%d、%H、%M、%S 都是代表时间格式的字符,具体含义如下:
- %Y:表示年份,4位数字
- %m:表示月份,数字为 01-12
- %d:表示日期,数字为 01-31
- %H:表示小时,数字为 00-23
- %M:表示分钟,数字为 00-59
- %S:表示秒数,数字为 00-59
3.格式化输出时间日期
Python 中的 datetime 模块可以用来处理时间日期的格式化输出。datetime 模块中包含了三个类:datetime、date 和 time。
代码示例:
import datetime
# 获取当前日期和时间
now = datetime.datetime.now()
# 将时间格式化输出
print("当前时间为:", now.strftime("%Y-%m-%d %H:%M:%S"))
# 输出年份、月份和日期
print("年份为:", now.year)
print("月份为:", now.month)
print("日期为:", now.day)
输出结果:
当前时间为: 2020-09-11 14:34:41 年份为: 2020 月份为: 9 日期为: 11
在上面的示例代码中,先用 datetime.datetime.now() 获取当前日期和时间的对象,然后使用 strftime() 的方法将其转换为指定的格式。同样的,还可以通过 year、month、day 等属性获取年月日等信息。
4.计算时间差
在 Python 中,可以使用 timedelta 对象计算两个日期或时间之间的时间差。
代码示例:
import datetime
# 获取当前时间
now = datetime.datetime.now()
# 计算时间差
delta = datetime.timedelta(days=7)
# 计算一周后的日期
future = now + delta
# 输出日期
print("当前时间为:", now)
print("一周后的日期为:", future)
输出结果:
当前时间为: 2020-09-11 14:42:31.279856 一周后的日期为: 2020-09-18 14:42:31.279856
在上述示例代码中,首先获取了当前时间,然后使用 timedelta 对象计算出 7 天后的时间,最后将其输出。
总结
本文介绍了 Python 中的一些时间日期函数,包括获取当前时间、转换时间格式、格式化输出日期时间、计算时间差等。掌握这些函数可以帮助我们更好地处理时间日期相关的任务,提高代码效率。
