简体   繁体   中英

finding difference in days between two dates

I want to know the difference in days between the following dates...can anyone provide inputs on how to achieve this?

CR created date
2013-11-01
Current date
2013-11-09 18:17:53.196126

First you have to change the input to a type that python knows - datetime . Then use the builtin functions.

>>> from datetime import datetime
>>> A = datetime.strptime('2013-11-01', '%Y-%m-%d')
>>> A
datetime.datetime(2013, 11, 1, 0, 0)
>>> B = datetime.strptime('2013-11-09 18:17:53.196126', '%Y-%m-%d %H:%M:%S.%f')
>>> B
datetime.datetime(2013, 11, 9, 18, 17, 53, 196126)
>>> diff = B - A
>>> diff
datetime.timedelta(8, 65873, 196126)
>>> diff.total_seconds()
757073.196126
>>> diff.total_seconds() / (60 * 60 * 24)
8.762421251458333

Use the datetime module. If you have a datetime.datetime object A , and a datetime.date object B , the difference is:

A.date() - B

Try it ;-)

Example:

>>> from datetime import datetime, date
>>> A = datetime.strptime("2013-11-09 18:17:53.196126", "%Y-%m-%d %H:%M:%S.%f")
>>> B = date(*map(int, "2013-11-01".split("-")))
>>> print A
2013-11-09 18:17:53.196126
>>> print B
2013-11-01
>>> print A.date() - B
8 days, 0:00:00

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