Python 如何将日期转换为datetime
本文将讨论在Python中如何将一个日期转换为一个datetime对象。
我们使用datetime模块中的combine方法,将一个 日期 和一个 时间 对象组合起来创建一个datetime对象。
语法
combine()方法的语法如下。
datetime.combine(date,time)
其中,
*date 是一个日期对象。
***time** 是一个时间对象。
这个方法返回一个datetime对象,它是上述两个对象(日期、时间)的组合。
将日期对象转换为datetime对象
如果我们有一个 date对象,但没有时间对象,那么可以使用datetime对象将时间对象初始化为最小值(最小值表示凌晨,即00:00:00)。
例子
在下面的示例代码中,我们使用 today() 方法检索到一个日期对象,并使用 min.time() 方法将时间对象初始化为最小时间(00:00:00)。然后,通过应用 datetime.combine() 方法将这两个对象组合起来。
from datetime import date
from datetime import datetime
my_date = date.today()
print("The date object:",my_date)
my_time = datetime.min.time()
print("The time object:",my_time)
my_datetime = datetime.combine(my_date, my_time)
print("The combined datetime object:",my_datetime)
输出
上述代码的输出如下。
The date object: 2022-05-19
The time object: 00:00:00
The combined datetime object: 2022-05-19 00:00:00
当给定日期和时间对象时
在这里,我们初始化了日期和时间对象。然后使用combine方法将其组合成一个datetime对象。
示例
在这个示例中,我们将在给定日期和时间对象时转换一个datetime对象。
import datetime
my_date = datetime.datetime(2012, 2, 12)
print("The date object:",my_date)
my_time = datetime.time(1, 30)
print("The time object:",my_time)
combined_datetime = my_date.combine(my_date, my_time)
print("The combined datetime object:",combined_datetime)
输出
上述代码的输出如下:
The date object: 2012-02-12 00:00:00
The time object: 01:30:00
The combined datetime object: 2012-02-12 01:30:00
使用datetime()
在Python中,datetime()构造函数接受年、月和日作为参数,并创建一个** datetime** 对象。
将所需日期对象的年、月和日值(例如my_date.year、my_date.month、my_date.day)传递给该构造函数,将日期对象转换为datetime对象。
示例
from datetime import date
from datetime import datetime
my_date = date.today()
my_datetime = datetime(my_date.year, my_date.month, my_date.day)
print(my_datetime)
输出
2022-09-05 00:00:00
了解更多关于Python日期和时间?请查阅我们的Python日期和时间教程。