如何从字符串中解析datetime和time,以及如何在Python中添加这些解析的datetime和time值

如何从字符串中解析datetime和time,以及如何在Python中添加这些解析的datetime和time值,python,datetime,time,timedelta,Python,Datetime,Time,Timedelta,我正在从字符串解析datetime对象, 在这种情况下,我面临一个问题,我必须将datetime对象与time对象一起添加,以创建组合的时间戳 我知道有一个datetime.combine方法,但不幸的是,我不能在这种情况下使用它 e、 g.有两个字符串,一个包含格式化的datetime,另一个包含格式化的time,如下所示 dt_str = "2018/11/27 14:12:32" tm_str = "1:23:45.678" # 1 hour 23 minutes 11 seconds a

我正在从字符串解析datetime对象, 在这种情况下,我面临一个问题,我必须将datetime对象与time对象一起添加,以创建组合的时间戳

我知道有一个datetime.combine方法,但不幸的是,我不能在这种情况下使用它

e、 g.有两个字符串,一个包含格式化的datetime,另一个包含格式化的time,如下所示

dt_str = "2018/11/27 14:12:32"
tm_str = "1:23:45.678" # 1 hour 23 minutes 11 seconds and 750 micro seconds
首先,我们需要从python的标准库(即datetime、time和timedelta)导入

import datetime, time
from datetime import timedelta
然后我们将dt_str解析为datetime对象,将tm_str解析为time对象

dt = datetime.datetime.strptime(dt_str, "%Y/%m/%d %H:%M:%S")
tm = time.strptime(tm_str, "%H:%M:%S.%f")
timestamp = dt + timedelta(hours=tm.tm_hour) + \
timedelta(minutes=tm.tm_min) + timedelta(seconds=tm.tm_sec)
现在,我们将使用timedelta类从time对象向datetime对象添加小时、分钟和秒

dt = datetime.datetime.strptime(dt_str, "%Y/%m/%d %H:%M:%S")
tm = time.strptime(tm_str, "%H:%M:%S.%f")
timestamp = dt + timedelta(hours=tm.tm_hour) + \
timedelta(minutes=tm.tm_min) + timedelta(seconds=tm.tm_sec)
结果

print("dt:", dt)
print("tm:", tm)
print("timestamp: ", timestamp)
注意:您不能添加微秒值,至少我不知道该方法。如果有人知道做上述操作的更好方法,请在下面列出您的解决方案

dt: 2018-11-27 14:12:32
tm: time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=1, tm_min=23, tm_sec=45, tm_wday=0, tm_yday=1, tm_isdst=-1)
timestamp: 2018-11-27 15:36:17

您仍然可以使用日期算法创建精确的timedelta对象。只要tm_str符合格式模式,即。