结合日期时间(与时间组件)和时间对象

时间:2017-05-17 02:17:46

标签: python datetime

好吧,我的日期时间对象包含 2013-10-01 14:15:00 等信息和时间对象

  1. 1900-01-01 00:00:49.235000
  2. 1900-01-01 00:00:49.465000
  3. 1900-01-01 00:00:49.695000
  4. 时间对象实际上是渐进式增量,我想将其添加到datetime对象中。如上所述here

      

    如果date是datetime对象,则忽略其时间组件和tzinfo属性。

    我写了下面的代码。应该如何更新以便能够将这些时间对象作为增量添加到datetime对象?

    def CombineDateTime(date_str, time_str, date_fmt, time_fmt, equipment, sample_name):
    
    import datetime
    
    try:
        date_obj = datetime.datetime.strptime(date_str, date_fmt)
    
        time_obj = datetime.datetime.strptime(time_str, time_fmt)
    
        return datetime.datetime.combine(date_obj.date(), time_obj.time())
    
    except:
        return 'Error'
    

    输出:

    1. 2013-10-01 00:00:49.235000
    2. 2013-10-01 00:00:49.465000
    3. 2013-10-01 00:00:49.695000
    4. 预期产出:

      1. 2013-10-01 14:15:49.235000
      2. 2013-10-01 14:15:49.465000
      3. 2013-10-01 14:15:49.695000

1 个答案:

答案 0 :(得分:1)

您获得的输出是因为datetime.datetime.combine()的2013-10-0100:00:49.235000,并且此时未考虑date_obj 14:15:00中的时间!

因此,您可以在结合之前将date_obj timedelta添加到time_obj中!

date_time=date_obj.time()
time_obj += datetime.timedelta(hours=date_time.hour,minutes=date_time.minute,seconds=date_time.second,microseconds=date_time.microsecond)

即,

def CombineDateTime(date_str, time_str, date_fmt, time_fmt, equipment, sample_name):
    import datetime
    try:
        date_obj = datetime.datetime.strptime(date_str, date_fmt)
        date_time=date_obj.time()

        time_obj = datetime.datetime.strptime(time_str, time_fmt)
        time_obj += datetime.timedelta(hours=date_time.hour,minutes=date_time.minute,seconds=date_time.second,microseconds=date_time.microsecond)

        return datetime.datetime.combine(date_obj.date(),time_obj.time())

    except Exception as e:
        #print e 
        return 'Error'