Why is datetime.strptime not working in this simple example?

PythonStringDatetimeType ConversionDatetime Format

Python Problem Overview


I'm using strptime to convert a date string into a datetime. According to the linked page, formatting like this should work:

>>> # Using datetime.strptime()
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")

My code is:

import datetime
dtDate = datetime.strptime(sDate,"%m/%d/%Y")

where sDate = "07/27/2012". (I understand, from the same page, that %Y is "Year with century as a decimal number.")

I have tried putting the actual value of sDate into the code:

dtDate = datetime.strptime("07/27/2012","%m/%d/%Y")

but this does not work. The error I get is:

> AttributeError: 'module' object has no attribute 'strptime'

What am I doing wrong?

Python Solutions


Solution 1 - Python

You should be using datetime.datetime.strptime. Note that very old versions of Python (2.4 and older) don't have datetime.datetime.strptime; use time.strptime in that case.

Solution 2 - Python

You are importing the module datetime, which doesn't have a strptime function.

That module does have a datetime object with that method though:

import datetime
dtDate = datetime.datetime.strptime(sDate, "%m/%d/%Y")

Alternatively you can import the datetime object from the module:

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

Note that the strptime method was added in python 2.5; if you are using an older version use the following code instead:

import datetime, time
dtDate = datetime.datetime(*time.strptime(sDate, "%m/%d/%Y")[:6])

Solution 3 - Python

Because datetime is the module. The class is datetime.datetime.

import datetime
dtDate = datetime.datetime.strptime(sDate,"%m/%d/%Y")

Solution 4 - Python

You should use strftime static method from datetime class from datetime module. Try:

import datetime
dtDate = datetime.datetime.strptime("07/27/2012", "%m/%d/%Y")

Solution 5 - Python

You can also do the following,to import datetime

from datetime import datetime as dt

dt.strptime(date, '%Y-%m-%d')

Solution 6 - Python

If in the folder with your project you created a file with the name "datetime.py"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionReinstate Monica - Goodbye SEView Question on Stackoverflow
Solution 1 - PythonecatmurView Answer on Stackoverflow
Solution 2 - PythonMartijn PietersView Answer on Stackoverflow
Solution 3 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 4 - PythonKonrad HałasView Answer on Stackoverflow
Solution 5 - PythonPriyanka MarihalView Answer on Stackoverflow
Solution 6 - PythonIhor IvasiukView Answer on Stackoverflow