[英]Difference between two timestamps with different weekdays?
I've the following dates:我有以下日期:
Tue 19:00-20:00
Wed 04:25-15:14
How can i get the difference between Tue 20:00
and Wed 04:25
?我怎样才能知道
Tue 20:00
和Wed 04:25
之间的区别?
I've tried to transform it in datetime
objects but since i don't have the day of the month or a year both objects will get the same date:我试图在
datetime
对象中对其进行转换,但由于我没有月份或年份的日期,因此两个对象都将获得相同的日期:
d1 = datetime.strptime("Tue 20:00", "%a %H:%M")
d2 = datetime.strptime("Wed 04:25", "%a %H:%M")
datetime.datetime(1900, 1, 1, 20, 0)
datetime.datetime(1900, 1, 1, 20, 0)
datetime.datetime(1900, 1, 1, 4, 25)
datetime.datetime(1900, 1, 1, 4, 25)
The difference in minutes should be 505
but in this case will be -935.0
because they have the same date, and so they differ by almost 16 hours and not about 8 and a half:分钟差应该是
505
,但在这种情况下会是-935.0
,因为它们具有相同的日期,因此它们相差近 16 小时而不是大约 8 个半小时:
diff = (d2 - d1).total_seconds() / 60 # -935.0
datetime.strptime()
can't do anything else, because the day of the week is not enough to form a date. datetime.strptime()
不能做任何其他事情,因为星期几不足以形成日期。 You'd need a week number and a year for a week-day to make any sense.您需要一个星期数和一个年份来表示工作日才有意义。 If you need to get the relative difference between two dates that are assumed to be in the same week , then any week number and year would do, eg:
如果您需要获取假定在同一周的两个日期之间的相对差异,那么任何周数和年份都可以,例如:
arbitrary_iso_week = "2020-25 "
d1 = datetime.strptime(arbitrary_iso_week + "Tue 20:00", "%G-%V %a %H:%M")
d2 = datetime.strptime(arbitrary_iso_week + "Wed 04:25", "%G-%V %a %H:%M")
This makes use of the %G
and %V
formatters for ISO 8601 week numbers .这利用了 ISO 8601 周数的
%G
和%V
格式化程序。
This produces datetime objects with a more meaningful date releationship:这将生成具有更有意义的日期关系的日期时间对象:
>>> arbitrary_iso_week = "2020-25 "
>>> d1 = datetime.strptime(arbitrary_iso_week + "Tue 20:00", "%G-%V %a %H:%M")
>>> d2 = datetime.strptime(arbitrary_iso_week + "Wed 04:25", "%G-%V %a %H:%M")
>>> d1
datetime.datetime(2020, 6, 16, 20, 0)
>>> d2
datetime.datetime(2020, 6, 17, 4, 25)
>>> (d2 - d1).total_seconds() / 60
505.0
The actual dates don't matter here, just their difference in days.实际日期在这里并不重要,只是它们的天数不同。
d1
is now earlier, not later, than d2
. d1
现在比d2
早,而不是晚。
You may have to take into account that week days are circular, in that you could have an earlier date on, say, Friday, and a later date on Monday.您可能必须考虑到工作日是循环的,因为您可以有一个更早的日期,比如星期五,而更晚的日期是星期一。 If you can assume that the first value must be earlier than the second, then the solution is simple.
如果您可以假设第一个值必须早于第二个值,那么解决方案很简单。 Just subtract 7 days from
d1
if it is later than d2
:如果晚于
d2
,只需从d1
中减去 7 天:
# if the first date must come before the second, then it must be one week earlier.
if d1 > d2:
d1 -= timedelta(days=7)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.