简体   繁体   中英

Calculate ISO 8601 time format to hours/minutes from now with Python

How would I receive an input of a string (time in ISO 8601 format) and convert/calculate the duration from then until now?

Input: 2018-09-29T00:33:33Z

Output: 3 days ago

Thanks.

from datetime import datetime
import dateutil.parser

a = datetime.now()
#a = datetime.strftime(a, format="%Y-%m-%d%H:%M:%S")
#a = a[:10] + 'T' + a[10:] + 'Z'
a = datetime.strftime(a, format="%Y-%m-%dT%H:%M:%SZ")

a = dateutil.parser.parse(a) - dateutil.parser.parse("2018-09-29T00:33:33Z")
print(str(a))

3 days, 2:00:00

An easier solution using Arrow .

>>> import arrow
>>> d = arrow.get("2018-09-29T00:33:33Z")
>>> d.humanize()
'3 days ago'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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