Python 将datetime.date对象与datetime.datetime对象中的时间字符串组合

Python 将datetime.date对象与datetime.datetime对象中的时间字符串组合,python,datetime,Python,Datetime,假设您有一个datetime.date对象,例如datetime.date.today返回的对象 然后,稍后还会得到一个表示时间的字符串,该字符串补充了date对象 在datetime.datetime对象中结合这两者的Python方式是什么?更具体地说,我可以避免将日期对象转换为字符串吗 以下是我目前的工作方式: def combine_date_obj_and_time_str(date_obj, time_str): # time_str has this form: 03:40:

假设您有一个datetime.date对象,例如datetime.date.today返回的对象

然后,稍后还会得到一个表示时间的字符串,该字符串补充了date对象

在datetime.datetime对象中结合这两者的Python方式是什么?更具体地说,我可以避免将日期对象转换为字符串吗

以下是我目前的工作方式:

def combine_date_obj_and_time_str(date_obj, time_str):
    # time_str has this form: 03:40:01 PM
    return datetime.datetime.strptime(date_obj.strftime("%Y-%m-%d") + ' ' + time_str, "%Y-%m-%d %I:%M:%S %p")
编辑:

我查看了datetime.datetime.combine,正如第一个答案所描述的,但我对将时间字符串放入时间对象有点不知所措:

>>> datetime.datetime.combine(datetime.date.today(), time.strptime("03:40:01 PM", "%I:%M:%S %p"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: combine() argument 2 must be datetime.time, not time.struct_time
>>> datetime.datetime.combine(datetime.date.today(), datetime.time.strptime("03:40:01 PM", "%I:%M:%S %p"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.time' has no attribute 'strptime'

如果您只是阅读文档,或者在交互式解释器中查看helpdatetime,您将看到以下方法:

classmethod datetime.combinedate,时间

返回一个新的datetime对象,其日期组件等于给定日期对象的日期组件,其时间组件和tzinfo属性等于给定时间对象的日期组件和tzinfo属性。对于任何datetime对象d,d==datetime.combined.date,d.timetz。如果date是datetime对象,则忽略其时间组件和tzinfo属性

因此,您不必自己编写方法;它已经在模块中了

当然,您需要将该time_str解析为一个time对象,但您显然已经知道如何做到这一点

但是,如果您确实想自己编写,那么将日期和时间格式化为字符串以重新解析它们将是愚蠢的。为什么不直接访问属性呢

return datetime(d.year, d.month, d.day, t.hour, t.minute. t.second, t.tzinfo)

如果您只是阅读文档,或者在交互式解释器中查看helpdatetime,您将看到以下方法:

classmethod datetime.combinedate,时间

返回一个新的datetime对象,其日期组件等于给定日期对象的日期组件,其时间组件和tzinfo属性等于给定时间对象的日期组件和tzinfo属性。对于任何datetime对象d,d==datetime.combined.date,d.timetz。如果date是datetime对象,则忽略其时间组件和tzinfo属性

因此,您不必自己编写方法;它已经在模块中了

当然,您需要将该time_str解析为一个time对象,但您显然已经知道如何做到这一点

但是,如果您确实想自己编写,那么将日期和时间格式化为字符串以重新解析它们将是愚蠢的。为什么不直接访问属性呢

return datetime(d.year, d.month, d.day, t.hour, t.minute. t.second, t.tzinfo)

如何获得该时间?@PascalvKooten:从sar的输出注意:time.strtime*args返回time.struct_time,而不是datetime.time。要得到后者,请调用datetime.strtime*args.time.@J.F.Sebastian great perfect这是我在这个特定实例中的最后一个谜题,我向用户abarnert提供的所有借口都是因为我没有阅读完整的datetime.datetime/datetime.date/datetime.time/time.struc_time/etc文档,并冒险就此提出问题,因此,按照这种思路,也许是时候让人们自己通过阅读文档和书籍来整理资料,而不是打扰其他用户了。。。如何获得该时间?@PascalvKooten:从sar的输出注意:time.strtime*args返回time.struct_time,而不是datetime.time。要得到后者,请调用datetime.strtime*args.time.@J.F.Sebastian great perfect这是我在这个特定实例中的最后一个谜题,我向用户abarnert提供的所有借口都是因为我没有阅读完整的datetime.datetime/datetime.date/datetime.time/time.struc_time/etc文档,并冒险就此提出问题,因此,按照这种思路,也许是时候让人们自己通过阅读文档和书籍来整理资料,而不是打扰其他用户了。。。