Hi team.
I am battling to convert a string to date. I currently manually pass a string date to my program(cobdate = string.replace(sys.argv[1], '-', '')) which will be used by a lot of things. The date will be in this format. "2012-02-02". I need to convert this to a proper date I can use to calculate how many days are between today's date(now = datetime.date.today()) and the date passed to the method by the user

import os
import datetime
import time
import logging
import sys
import platform
import string

now = datetime.date.today()
print TT
aa = now/TT #I want to check how many days there are between the date passed to the method and today's date
print aa

Problem is that I cannot use "aa = now-TT" because TT is a string. I also tried (TT = datetime.strptime('2012-01-16', '%Y-%m-%d')) but they are all not working. What am I missing here. When I print now, it comes up as 2012-02-29. Thank you so much in advance

Recommended Answers

All 2 Replies

Make TT a datetime object with strptime.
Change to datetime.now().
Now we have 2 datetime object that we can subtract.

>>> from datetime import datetime
>>> TT = "2012-01-16"
>>> tt_date = datetime.strptime(TT, '%Y-%m-%d')
>>> tt_date
datetime.datetime(2012, 1, 16, 0, 0)
>>> now = datetime.now()
>>> now
datetime.datetime(2012, 2, 29, 21, 4, 29, 491000)
>>> print now - tt_date
44 days, 21:04:29.491000

snipssat. Thank you so much for this. Really helped me a lot.
Here is the final change and it is working 100%

TT = sys.argv[1]
tt_date = datetime.strptime(TT, '%Y-%m-%d')
print tt_date
now = datetime.now()
print now
print now - tt_date

if now - tt_date >= timedelta(2):
    print "fantastic"
    print "less than 2 days"
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.