一、使用time模块获取系统时间
# 导入time模块
import time
# 获取系统当前时间戳(从1970年1月1日至今的秒数)
timestamp = time.time()
print("当前时间戳为:", timestamp)
# 将时间戳转换为日期时间格式
local_time = time.localtime(timestamp)
print("本地时间为:", time.strftime("%Y-%m-%d %H:%M:%S", local_time))
time模块是Python内置的用于处理时间的模块,通过导入time模块就可以利用其中的函数来获取系统时间。其中,time.time()函数可以获取当前时间戳,即从1970年1月1日至今的秒数。另外,time.localtime()函数可以将时间戳转换为本地日期时间格式。通过传递不同的格式化参数,time.strftime()函数可以实现将本地时间格式化输出。
二、使用datetime模块获取系统时间
# 导入datetime模块
import datetime
# 获取当前日期时间
now = datetime.datetime.now()
print("当前日期时间为:", now)
# 将日期时间格式化输出
print("本地日期时间为:", now.strftime("%Y-%m-%d %H:%M:%S"))
datetime模块也是Python内置的用于处理日期时间的模块。通过导入datetime模块,可以直接调用datetime.datetime.now()函数获取当前日期时间。并且同样可以利用strftime()函数将日期时间格式化输出为特定格式。
三、使用arrow模块获取系统时间
# 导入arrow模块
import arrow
# 获取当前日期时间
now = arrow.now()
print("当前日期时间为:", now)
# 将日期时间格式化输出
print("本地日期时间为:", now.format("YYYY-MM-DD HH:mm:ss"))
arrow模块是Python第三方库,功能类似于datetime模块,但是用法更加简单,支持更多的日期时间格式化选项。通过导入arrow模块,可以直接调用arrow.now()函数获取当前日期时间,并且调用format()函数将日期时间格式化输出为特定格式。
四、使用pandas模块获取系统时间
# 导入pandas模块
import pandas as pd
# 获取当前系统时间
now = pd.Timestamp.now()
print("当前系统时间为:", now)
# 将日期时间格式化输出
print("本地日期时间为:", now.strftime("%Y-%m-%d %H:%M:%S"))
pandas模块是Python第三方库,主要用于数据分析和处理。虽然不是专门用于处理日期时间的模块,但它可以利用pd.Timestamp.now()函数获取当前系统时间,pd.to_datetime()函数将日期时间格式化输出。
五、使用calendar模块获取系统时间
# 导入calendar模块
import calendar
# 获取当前系统时间
now = calendar.timegm(time.gmtime())
print("当前系统时间为:", now)
# 将时间戳转换为日期时间格式
local_time = time.localtime(now)
print("本地日期时间为:", time.strftime("%Y-%m-%d %H:%M:%S", local_time))
calendar模块也是Python内置的用于处理日期时间的模块。通过导入calendar模块,可以利用time.gmtime()函数获取当前系统时间,并且通过calendar.timegm()函数将时间转换为时间戳。最后同样可以用localtime()函数将时间戳转换为本地日期时间格式。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/258672.html