使用 timedelta 将时间减少 5 分钟
reduce 5 minutes from time using timedelta
计算时间后想要打印时间小于 5 分钟:
now = datetime(2020,11,9,13,38,18)
t0 = datetime.strptime((now - timedelta(minutes =(now.minute - (now.minute - (now.minute % 5))), seconds = now.second)).strftime("%Y-%m-%d %H:%M:%S"),"%Y-%m-%d %H:%M:%S") #getting the time in multiples of 5 i.e 13:35:00
t1 = (t0 - timedelta(minutes = (t0.minute - 5))) #reducing 5 mins i.e 13:30:00
print(t0)
print(t1)
t0 给出了预期的结果,但 t1 打印了 13:05:00,但它应该是 13:30:00
如果我理解正确你的问题你可以这样做:
now = datetime(2020,11,9,13,38,18)
t0 = datetime.strptime((now - timedelta(minutes =(now.minute - (now.minute - (now.minute % 5))), seconds = now.second)).strftime("%Y-%m-%d %H:%M:%S"),"%Y-%m-%d %H:%M:%S") #getting the time in multiples of 5 i.e 13:35:00
t1 = t0 - timedelta(minutes=5)
print(t1)
>>> datetime.datetime(2020, 11, 9, 13, 30)
基本上,如果您想从日期时间对象中“删除”5 分钟,您可以使用 timedelta 传递分钟数作为参数(在本例中为 5)。
结果是另一个日期时间对象。如果需要,您可以根据需要将其格式化为字符串。
您的代码是错误的,因为这样您将“删除”25 分钟 (t0.minute = 30 - 5)
计算时间后想要打印时间小于 5 分钟:
now = datetime(2020,11,9,13,38,18)
t0 = datetime.strptime((now - timedelta(minutes =(now.minute - (now.minute - (now.minute % 5))), seconds = now.second)).strftime("%Y-%m-%d %H:%M:%S"),"%Y-%m-%d %H:%M:%S") #getting the time in multiples of 5 i.e 13:35:00
t1 = (t0 - timedelta(minutes = (t0.minute - 5))) #reducing 5 mins i.e 13:30:00
print(t0)
print(t1)
t0 给出了预期的结果,但 t1 打印了 13:05:00,但它应该是 13:30:00
如果我理解正确你的问题你可以这样做:
now = datetime(2020,11,9,13,38,18)
t0 = datetime.strptime((now - timedelta(minutes =(now.minute - (now.minute - (now.minute % 5))), seconds = now.second)).strftime("%Y-%m-%d %H:%M:%S"),"%Y-%m-%d %H:%M:%S") #getting the time in multiples of 5 i.e 13:35:00
t1 = t0 - timedelta(minutes=5)
print(t1)
>>> datetime.datetime(2020, 11, 9, 13, 30)
基本上,如果您想从日期时间对象中“删除”5 分钟,您可以使用 timedelta 传递分钟数作为参数(在本例中为 5)。
结果是另一个日期时间对象。如果需要,您可以根据需要将其格式化为字符串。
您的代码是错误的,因为这样您将“删除”25 分钟 (t0.minute = 30 - 5)