欢迎访问宙启技术站
智能推送

使用Python获取当前时间和日期的函数

发布时间:2023-10-11 02:05:41

Python中获取当前时间和日期的函数有多种方式,下面将介绍其中常用的几种方法。

1. 使用datetime模块:

import datetime

# 获取当前时间和日期
now = datetime.datetime.now()
print("当前时间和日期:", now)

# 获取当前时间
current_time = now.strftime("%H:%M:%S")
print("当前时间:", current_time)

# 获取当前日期
current_date = now.strftime("%Y-%m-%d")
print("当前日期:", current_date)

在上述代码中,首先导入了datetime模块,然后使用datetime.datetime.now()函数获取当前时间和日期的datetime对象并赋值给变量now。接着使用strftime()方法将时间和日期格式化成指定的字符串格式,"%H:%M:%S"表示小时:分钟:秒,"%Y-%m-%d"表示年-月-日。

2. 使用time模块:

import time

# 获取当前时间和日期的时间戳
timestamp = time.time()
print("当前时间和日期的时间戳:", timestamp)

# 将时间戳转换为可读的时间和日期
local_time = time.localtime(timestamp)
current_time = time.strftime("%H:%M:%S", local_time)
current_date = time.strftime("%Y-%m-%d", local_time)
print("当前时间:", current_time)
print("当前日期:", current_date)

在上述代码中,导入了time模块,使用time.time()函数获取当前时间和日期的时间戳。然后使用time.localtime()函数将时间戳转换为本地时间的struct_time对象,再使用strftime()方法将时间和日期格式化成指定的字符串格式。

3. 使用calendar模块:

import calendar

# 获取当前时间和日期
now = calendar.datetime.datetime.now()
print("当前时间和日期:", now)

# 获取当前时间
current_time = now.strftime("%H:%M:%S")
print("当前时间:", current_time)

# 获取当前日期
current_date = now.strftime("%Y-%m-%d")
print("当前日期:", current_date)

在上述代码中,导入了calendar模块,使用calendar.datetime.datetime.now()函数获取当前时间和日期的datetime对象并赋值给变量now。接着使用strftime()方法将时间和日期格式化成指定的字符串格式。

4. 使用arrow模块:

import arrow

# 获取当前时间和日期
now = arrow.now()
print("当前时间和日期:", now)

# 获取当前时间
current_time = now.format("HH:mm:ss")
print("当前时间:", current_time)

# 获取当前日期
current_date = now.format("YYYY-MM-DD")
print("当前日期:", current_date)

在上述代码中,首先需要安装arrow模块,使用pip install arrow命令进行安装。然后导入arrow模块,使用arrow.now()函数获取当前时间和日期的arrow对象并赋值给变量now。接着使用format()方法将时间和日期格式化成指定的字符串格式。

总结:

以上介绍了四种常用的方法来获取当前时间和日期的函数,分别使用了datetime、time、calendar和arrow模块。根据实际需求选择合适的方法来使用。它们的输出结果类似,都可以获取到当前的时间和日期。