Python中的日期和时间函数:如何获取当前时间?
发布时间:2023-07-06 16:24:21
Python提供了多种方式来获取当前时间。以下是常用的方法:
1. 使用datetime模块:
import datetime now = datetime.datetime.now() print(now)
输出结果类似于:2021-01-01 12:30:45.123456
可以使用now.year、now.month、now.day、now.hour、now.minute、now.second等属性获取当前时间的年、月、日、小时、分钟、秒。
2. 使用time模块:
import time now = time.localtime() print(now)
输出结果类似于:time.struct_time(tm_year=2021, tm_mon=1, tm_mday=1, tm_hour=12, tm_min=30, tm_sec=45, tm_wday=4, tm_yday=1, tm_isdst=0)
可以使用now.tm_year、now.tm_mon、now.tm_mday、now.tm_hour、now.tm_min、now.tm_sec等属性获取当前时间的年、月、日、小时、分钟、秒。
3. 使用calendar模块:
import calendar now = calendar.timegm(time.gmtime()) print(now)
输出结果为当前时间的UNIX时间戳,即从1970年1月1日开始经过的秒数。
4. 使用date模块:
import date now = date.today() print(now)
输出结果类似于:2021-01-01
以上方法都可以使用不同的格式化选项来获取自定义的时间格式,例如:
# 使用strftime方法格式化时间
formatted_time = now.strftime('%Y-%m-%d %H:%M:%S')
print(formatted_time)
输出结果类似于:2021-01-01 12:30:45
以上是获取当前时间的几种常用方法,在具体应用中可以根据需求选择合适的方法。
