Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 407
Reinstate Monica - Goodbye SE Avatar asked Aug 22 '12 09:08

Reinstate Monica - Goodbye SE


People also ask

How does datetime Strptime work?

The strptime() function in Python is used to format and return a string representation of date and time. It takes in the date, time, or both as an input, and parses it according to the directives given to it. It raises ValueError if the string cannot be formatted according to the provided directives.

What does the Strptime function do?

The strptime() function converts the character string pointed to by buf to values that are stored in the tm structure pointed to by tm, using the format specified by format. The format contains zero or more directives.

What is Strptime short for?

strptime() -> string parsed time.

How do I use Strftime and Strptime in Python?

Python time strptime() MethodThe format parameter uses the same directives as those used by strftime(); it defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime(). If string cannot be parsed according to format, or if it has excess data after parsing, ValueError is raised.


Video Answer


1 Answers

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.

like image 195
ecatmur Avatar answered Oct 18 '22 14:10

ecatmur