[英]Python human readable date difference
I have given date strings like these:我给出了这样的日期字符串:
Mon Jun 28 10:51:07 2010
Fri Jun 18 10:18:43 2010
Wed Dec 15 09:18:43 2010
Sample usage: 样品用法:
from datetime import datetime
my_date = datetime.strptime('Mon Jun 28 10:51:07 2010', '%a %b %d %H:%M:%S %Y')
print my_date
EDIT: 编辑:
You could also print the time difference in a human readable form, like so: 您还可以用人类可读的形式打印时差,如下所示:
from time import strptime
from datetime import datetime
def date_diff(older, newer):
"""
Returns a humanized string representing time difference
The output rounds up to days, hours, minutes, or seconds.
4 days 5 hours returns '4 days'
0 days 4 hours 3 minutes returns '4 hours', etc...
"""
timeDiff = newer - older
days = timeDiff.days
hours = timeDiff.seconds/3600
minutes = timeDiff.seconds%3600/60
seconds = timeDiff.seconds%3600%60
str = ""
tStr = ""
if days > 0:
if days == 1: tStr = "day"
else: tStr = "days"
str = str + "%s %s" %(days, tStr)
return str
elif hours > 0:
if hours == 1: tStr = "hour"
else: tStr = "hours"
str = str + "%s %s" %(hours, tStr)
return str
elif minutes > 0:
if minutes == 1:tStr = "min"
else: tStr = "mins"
str = str + "%s %s" %(minutes, tStr)
return str
elif seconds > 0:
if seconds == 1:tStr = "sec"
else: tStr = "secs"
str = str + "%s %s" %(seconds, tStr)
return str
else:
return None
older = datetime.strptime('Mon Jun 28 10:51:07 2010', '%a %b %d %H:%M:%S %Y')
newer = datetime.strptime('Tue Jun 28 10:52:07 2010', '%a %b %d %H:%M:%S %Y')
print date_diff(older, newer)
Original source for the time snippet. 时间片段的原始来源 。
>>> import datetime
>>> a = datetime.datetime.strptime("Mon Jun 28 10:51:07 2010", "%a %b %d %H:%M:%S %Y")
>>> b = datetime.datetime.strptime("Fri Jun 18 10:18:43 2010", "%a %b %d %H:%M:%S %Y")
>>> c = a-b
>>> c.days
10
#!/usr/bin/env python
import datetime
def hrdd(d1, d2):
"""
Human-readable date difference.
"""
_d1 = datetime.datetime.strptime(d1, "%a %b %d %H:%M:%S %Y")
_d2 = datetime.datetime.strptime(d2, "%a %b %d %H:%M:%S %Y")
diff = _d2 - _d1
return diff.days # <-- alternatively: diff.seconds
if __name__ == '__main__':
d1 = "Mon Jun 28 10:51:07 2010"
d2 = "Fri Jun 18 10:18:43 2010"
d3 = "Wed Dec 15 09:18:43 2010"
print hrdd(d1, d2)
# ==> -11
print hrdd(d2, d1)
# ==> 10
print hrdd(d1, d3)
# ==> 169
# ...
This isn't along the same lines as the other answers, but it might be helpful to someone wanting to display something more human readable (and less precise). 这与其他答案不同,但对于想要展示更具人类可读性(且更不精确)的人来说,它可能会有所帮助。 I did this quickly, so suggestions welcome. 我很快就这样做了,欢迎提出建议。
(Note that it assumes until_seconds
is the later timestamp.) (请注意,它假设until_seconds
是更晚的时间戳。)
def readable_delta(from_seconds, until_seconds=None):
'''Returns a nice readable delta.
readable_delta(1, 2) # 1 second ago
readable_delta(1000, 2000) # 16 minutes ago
readable_delta(1000, 9000) # 2 hours, 133 minutes ago
readable_delta(1000, 987650) # 11 days ago
readable_delta(1000) # 15049 days ago (relative to now)
'''
if not until_seconds:
until_seconds = time.time()
seconds = until_seconds - from_seconds
delta = datetime.timedelta(seconds=seconds)
# deltas store time as seconds and days, we have to get hours and minutes ourselves
delta_minutes = delta.seconds // 60
delta_hours = delta_minutes // 60
## show a fuzzy but useful approximation of the time delta
if delta.days:
return '%d day%s ago' % (delta.days, plur(delta.days))
elif delta_hours:
return '%d hour%s, %d minute%s ago' % (delta_hours, plur(delta_hours), delta_minutes, plur(delta_minutes))
elif delta_minutes:
return '%d minute%s ago' % (delta_minutes, plur(delta_minutes))
else:
return '%d second%s ago' % (delta.seconds, plur(delta.seconds))
def plur(it):
'''Quick way to know when you should pluralize something.'''
try:
size = len(it)
except TypeError:
size = int(it)
return '' if size==1 else 's'
Try this: 试试这个:
>>> (datetime.datetime.strptime("Mon Jun 28 10:51:07 2010", "%a %b %d %H:%M:%S %Y") - datetime.datetime.strptime("Fri Jun 18 10:18:43 2010", "%a %b %d %H:%M:%S %Y")).days
10
from datetime import datetime
resp = raw_input("What is the first date ?")
date1 = datetime.strptime(resp,"%a %b %d %H:%M:%S %Y")
resp2 = raw_input("What is the second date ?")
date2 = datetime.strptime(resp2,"%a %b %d %H:%M:%S %Y")
res = date2-date1
print str(res)
For details on how to print a timedelta object better, you can see this previous post . 有关如何更好地打印timedelta对象的详细信息,您可以看到此前一篇文章 。
Here is an improved version of date_diff() routine by @the_void.这是@the_void 改进的 date_diff() 例程。 It will print difference in the following fashion depending on how much the difference is:它将以以下方式打印差异,具体取决于差异的大小:
1d
12 sec
30 min 12 sec
3h 30m
5d 3h 30m
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.