如何获取日期python

原创
admin 20小时前 阅读数 2 #Python

如何获取日期Python

Python中,获取当前日期和时间是非常简单的任务,有多种方法可以实现,以下是其中几种常见的方法。

方法一:使用datetime模块

Python内置的datetime模块可以帮助我们获取当前日期和时间,使用datetime.datetime.now()函数可以获取当前的日期和时间。

示例代码:

import datetime
获取当前日期和时间
now = datetime.datetime.now()
输出结果
print("当前日期和时间:", now)

方法二:使用time模块

time模块也可以帮助我们获取当前时间,使用time.time()函数可以获取当前的时间戳,然后使用time.localtime()函数将其转换为本地时间。

示例代码:

import time
获取当前时间戳
current_time = time.time()
将时间戳转换为本地时间
local_time = time.localtime(current_time)
输出结果
print("当前时间:", local_time)

方法三:使用calendar模块

calendar模块可以帮助我们获取当前日期和星期几,使用calendar.weekday()函数可以获取当前星期几,使用calendar.date()函数可以获取当前日期。

示例代码:

import calendar
获取当前日期和星期几
current_date = calendar.date(2023, 7, 5)
current_weekday = calendar.weekday(current_date)
输出结果
print("当前日期:", current_date)
print("当前星期几:", current_weekday)
作者文章
热门
最新文章