11

I have the following 2 different datetime uses:

date=request.GET.get('date','')
    if date:
        date = datetime.strptime(date, "%m/%d/%Y")
        print date
    else:
        date = datetime.date.today()

It seems the imports needed are:

from datetime import datetime
date = datetime.strptime(date, "%m/%d/%Y")

and

import datetime
date = datetime.date.today()

I can't have both:

from datetime import datetime
import datetime

or one overrides the other.

If I have one, I get the error: object has no attribute today

How can I use both these datetime functions?

Atma
  • 29,141
  • 56
  • 198
  • 299

3 Answers3

18

You can alias the import names to ensure they're used differently. This is one of the reasons why datetime gets its fair share of criticism in the Python community.

What about:

from datetime import datetime as dt
import datetime

These will represent two separate things. AS shown by dir(dt) and dir(datetime)

Viktor Chynarov
  • 461
  • 2
  • 9
7

Removing .date. from your code should work:

from datetime import datetime

print datetime.strptime("12/31/2000", "%m/%d/%Y")
print datetime.today()

Output:

2000-12-31 00:00:00
2014-08-16 22:36:28.593481
Falko
  • 17,076
  • 13
  • 60
  • 105
5

In the case of datetime, you should always import the module itself, precisely to avoid this confusion.

import datetime
date = datetime.datetime.strptime(date, "%m/%d/%Y")
date = datetime.date.today()
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895