开发者

how to convert and subtract dates, times in python

开发者 https://www.devze.com 2023-04-10 19:40 出处:网络
I have the following date/time: 2011-09-27 13:42:16 I need to convert it to: 9/27/2011 13:42:16 I also need to be able to subtract one date from another and get the result in HH:MM:SS format.

I have the following date/time:

2011-09-27 13:42:16

I need to convert it to:

9/27/2011 13:42:16

I also need to be able to subtract one date from another and get the result in HH:MM:SS format. I have tried to use the dateutil.parser.parse function, and it parses the date fine but sadly it doesn't seem to get the time correctly. I also tried to use another method I found on stackoverflow that uses "time", but I get开发者_如何学JAVA an error that time is not defined.


You can use datetime's strptime function:

from datetime import datetime

date = '2011-09-27 13:42:16'
result = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')

You were lucky, as I had that above line written for a project of mine.

To print it back out, try strftime:

print result.strftime('%m/%d/%Y %H:%M:%S')


Use python-dateutil:

import dateutil.parser as dateparser

mydate = dateparser.parse("2011-09-27 13:42:16",fuzzy=True)
print(mydate.strftime('%m/%d/%Y T%H:%M:%S'))


http://docs.python.org/library/datetime.html#datetime.datetime.strptime

and

http://docs.python.org/library/datetime.html#datetime.datetime.strftime

(And the rest of the datetime module.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号