0

I know questions like these get asked all the time, but my specific problem doesn't seem to come up (at least I can't find it).

So my problem is like this. I have a MySQL database which has lots of data in it, with one column being full of dates. When I pull these dates, I automatically store them into a list which works great.

But, I also have to format the dates to calculate with. For instance, if I work on one of the dates I may need to extract just the month number. Having imported datetime, I would have imagined it was simple with strftime, but it wasn't. The problem is that they are stored in a string format (list is called last_shipped).

The dates come into the list according to this format:

((datetime.datetime(2012, 11, 30, 0, 0),),)

So when I try and use strftime I get the error

TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'

My question is, how do I convert a list full of these to a list of workable datetime objects?

Thanks in advance

EDIT:

I am using MySQLdb. An example of the code I have tried that produces the error above is:

z = datetime.datetime.strftime(gr, '%m')

In this case z is the datetime string I mentioned above.

5
  • 1
    "So when I try and use strftime". Show us what you tried, please Commented Nov 13, 2013 at 6:01
  • 1
    strftime is for creating strings; you want strptime to parse strings (and create datetime objects from the strings). Commented Nov 13, 2013 at 6:02
  • Are you using python's MySQLdb? Commented Nov 13, 2013 at 6:08
  • 2
    See stackoverflow.com/questions/466345/… Commented Nov 13, 2013 at 6:08
  • Are you storing the dates in a text field or something? Commented Nov 13, 2013 at 6:10

1 Answer 1

1

This will help you:

time.strptime(string[, format])

Parse a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime().

time.strftime(format[, t])

Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument.

Sign up to request clarification or add additional context in comments.

1 Comment

I've just used strptime and works a treat. Thanks for saving my early baldness. Can't believe I missed it, the price for being a newbie

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.