简体   繁体   English

python 中两个不同日期之间的差异

[英]Difference between two different dates in python

I want to write a function that finds the difference between two different time stamps in the following form: "October 5th 2019, 10:13:24 am".我想写一个 function 以以下形式找到两个不同时间戳之间的差异:“2019 年 10 月 5 日,上午 10:13:24”。 The difference between the two times will rarely be more than 15 minutes, but some times may go between days or years.两次之间的差异很少会超过 15 分钟,但有时可能会在几天或几年之间。 For example, the difference between "December 31st 2017, 11:58:26 pm" and "January 1st 2018, 00:04:56 am".例如,“2017 年 12 月 31 日,晚上 11:58:26”和“2018 年 1 月 1 日,00:04:56”之间的差异。 I was trying to use datetime and strptime but I can't get it to work.我试图使用 datetime 和 strptime 但我无法让它工作。

a = [{"time":"October 5th 2019, 10:13:24 am"},{"time":"October 5th 2019, 10:17:05 am"}] 

def difference(n): 
    for i in range(len(n)-1): 
        date1 = n[i].get("time") 
        date2 = n[i+1].get("time") 
        time1 = datetime.strptime(date1, '%m /%d /%y %H:%M:%S') 
        time2 = datetime.strptime(date2, '%m /%d /%y %H:%M:%S') 
    diff = time2 - time1 
    return diff

The table of all the formatting strings you can use with strptime is here: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior .您可以与strptime使用的所有格式字符串的表在这里: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

Note that it does have support to specify a month as a string like "October" instead of a number like "10", but you have to use "%B" instead of "%m".请注意,它确实支持将月份指定为像“October”这样的字符串而不是像“10”这样的数字,但是您必须使用“%B”而不是“%m”。 It's very important for the formatting string to exactly match the format of the input you're providing.格式化字符串与您提供的输入格式完全匹配非常重要。

Similarly, you can specify a time as AM/PM instead of 24-hour, but you need to use "%I" and "%p" instead of "%H".同样,您可以将时间指定为 AM/PM 而不是 24 小时制,但您需要使用“%I”和“%p”而不是“%H”。

datetime.strptime doesn't handle a date in a format like "5th", so you have to do a little re.sub to remove that piece, but once you've stripped off the letters you can use "%d": datetime.strptime不处理像“5th”这样的格式的日期,所以你必须做一点re.sub来删除那个部分,但是一旦你去掉了字母,你就可以使用“%d”:

>>> from datetime import datetime
>>> import re
>>> a = [{"time":"October 5th 2019, 10:13:24 am"},{"time":"October 5th 2019, 10:17:05 am"}]
>>> def parse_date(date: str) -> datetime:
...     return datetime.strptime(
...         re.sub(r" (\d+)[a-z]+ ", r" \1 ", date),
...         "%B %d %Y, %I:%M:%S %p"
...     )
...
>>> parse_date(a[1]["time"]) - parse_date(a[0]["time"])
datetime.timedelta(seconds=221)

The difference between 2 datetime.datetime objects is represented with datetime.timedelta . 2 个datetime.datetime对象之间的差异用datetime.timedelta表示。 From the official documentation :官方文档

A timedelta object represents a duration, the difference between two dates or times.

It holds only days, seconds, and microseconds .它只保存天、秒和微秒 You can then process that information as you desire.然后,您可以根据需要处理该信息。 For example,例如,

>>> from datetime import date
>>> d1=date(2012, 12, 4)
>>> d2=date(2015,10,9)
>>> d1-d2 # the difference will be negative(past-future)
datetime.timedelta(-1039)
>>> d2-d1 # the difference is positive (future-past)
datetime.timedelta(1039)
>>> delta=d2-d1
>>> delta.days, delta.seconds,delta.microseconds
(1039, 0, 0) # no seconds and microseconds as the difference can be shown in days only

For processing that number and formatting it the right way you can look at this question on Stack Overflow.要处理该数字并以正确的方式对其进行格式化,您可以在 Stack Overflow 上查看这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM