Reputation: 25659
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'
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".
Upvotes: 3
Views: 13575
Reputation: 11206
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
Upvotes: 6
Reputation: 2229
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')
Upvotes: 4