说我有一些格式的字符串%H:%M:%S
,例如04:35:45
.我想将它们转换为datetime.datetime
对象,年/月/日是一样的datetime.datetime.now()
.
我试过了
now = datetime.now() datetime_obj = datetime.strptime(time_string, "%H:%M:%S") datetime_obj.year = now.year datetime_obj.month = now.month datetime_obj.day = now.day
这year/month/day
是不可行的,因为它是只读属性.那么什么是最好的解决方案呢?
你想要datetime.combine(date, time)
:
>>> time = datetime.datetime.strptime("04:35:45", "%H:%M:%S").time() >>> time datetime.time(4, 35, 45) >>> day = datetime.datetime.now().date() >>> day datetime.date(2016, 1, 6) >>> datetime.datetime.combine(day, time) datetime.datetime(2016, 1, 6, 4, 35, 45) >>>