开发者

Python datetime in reverse

开发者 https://www.devze.com 2023-02-27 11:25 出处:网络
y=(datetime.datetime.now() ).strftime(\"%y%m%d\") gives \'110418\' I have data that reads \'110315\' and \'110512\', not trying to create it.
y=(datetime.datetime.now() ).strftime("%y%m%d")

gives '110418'

I have data that reads '110315' and '110512', not trying to create it.

How do I change '110418' 开发者_Go百科into date time so I can subtract

from '2011-07-15' (str)

import datetime

t = datetime.datetime.today()
print type(t)

tdate =datetime.datetime.strptime('110416', '%y%m%d') 
print type(tdate)

d =t-tdate
print d  

gives me

3 days, 15:14:38.921000

I need just "3".


You can convert any string representation into a datetime object using the strptime method.

Here's an example converting your string above into a datetime object:

import datetime

my_date = datetime.datetime.strptime('2011-07-15', '%Y-%m-%d')

Now you'll have a datetime object which can be subtracted against other datetime objects naturally.

If you're subtracting two dates, Python produces a datetime.timedelta object. You can then strip all of this away to just the days by doing print d.days in your example above.

For further info on what you can do with the datetime library, see: http://docs.python.org/library/datetime.html


I'm not completely sure I understood your question, but if you want to parse a string into a time object, you can use strptime:

import time
time.strptime('2011-07-15', '%Y-%m-%d')
0

精彩评论

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