Python 获取当前日期时间的各个组成部分的程序
在Python中,我们有一些内置的时间函数,例如datetime()、today()、now()和strftime(),可以用来获取当前日期时间的各个组成部分。当前日期时间的各个组成部分指的是确切的现在时间和日期。为了解决这种类型的问题,我们将使用一些与模块datetime相关的预定义方法。例如- 当前日期和时间对任何工作文化都很重要。
语法
以下示例中使用的语法如下所示―
datetime.now()
这是Python中预定义的方法,包括年、月、日、小时、分钟和秒。
strftime("%Y-%m-%d %H:%M:%S")
该方法通过导入datetime模块来表示日期和时间。
today()
这是Python中使用的预定义方法,它返回当前本地日期。当定义了模块“from datetime import date”时使用这个方法。
now()
现在(now())是Python中的一个内置函数,主要用于找到当前的日期和时间。
示例1
在以下示例中,我们将通过导入一个名为 datetime 的模块来启动程序。然后使用必要的变量’now’并使用预定义的 ‘datetime.datetime.now()’ 方法来找到本地的日期和时间。接下来,打印now变量的各个组成部分,如now.year、now.month、now.day、now.hour、now.minute和now.second以获得结果。
import datetime
# Obtain the current date and time
now = datetime.datetime.now()
# Print individual components of current date and time
print("The individual components of the current date and time are:")
print("Year:", now.year)
print("Month:", now.month)
print("Day:", now.day)
print("Hour:", now.hour)
print("Minute:", now.minute)
print("Second:", now.second)
输出
The individual components of the current date and time are:
Year: 2023
Month: 5
Day: 30
Hour: 21
Minute: 31
Second: 26
示例2
在下面的示例中,我们将通过从名为 datetime 的模块中导入datetime的所有内容来启动程序,这将找到当前时间。然后,它将从 datetime 模块中导入日期,以找到当前日期。然后初始化名为 tm 的变量,通过使用 datetime.now() 的预定义方法来计算当前时间。继续使用 strftime() 方法来找到时间格式,并将其作为 tm 的对象存储在变量 current_time 中。最后,我们分别打印个别的日期和时间以获得结果。
from datetime import datetime
from datetime import date
# Find the current date and time
tm = datetime.now()
# Create the time format in 12-hour format
# %I for 12-hour format, %p for AM/PM
current_time = tm.strftime("%I:%M:%S %p")
# Print individual components
print("The individual components of the current date are:")
print("Year:", tm.year)
print("Month:", tm.month)
print("Day:", tm.day)
print("The individual components of the current time are:")
print("Hour:", tm.strftime("%I"))
print("Minute:", tm.strftime("%M"))
print("Second:", tm.strftime("%S"))
print("AM/PM:", tm.strftime("%p"))
输出
The individual components of the current date are:
Year: 2023
Month: 5
Day: 30
The individual components of the current time are:
Hour: 09
Minute: 42
Second: 27
AM/PM: PM
示例3
安装要求
pip install arrow
上述命令是必需的,以便安装并运行此示例程序。
在下面的示例中,开始导入名为arrow的模块,该模块将帮助提供其内置函数。然后使用带有箭头模块的内置功能now()在变量date中。接下来,分别打印日期和时间格式,并获取结果。
import arrow
# Get the current date and time
date = arrow.now()
# Print individual components
print("The individual components of the current date:")
print("Year:", date.year)
print("Month:", date.month)
print("Day:", date.day)
print("The individual components of the current time:")
print("Hour:", date.hour)
print("Minute:", date.minute)
print("Second:", date.second)
输出
The individual components of the current date:
Year: 2023
Month: 5
Day: 30
The individual components of the current time:
Hour: 16
Minute: 19
Second: 5
结论
上述的两个输出展示了通过使用与名为datetime的模块相关的一些预定义方法来显示当前日期和时间的结果。为了格式化时间格式,它使用了strftime()方法。这个方法还返回一个日期的格式。还有一个名为arrow的模块,它也能帮助设置当前日期时间的各个组成部分。