Xtremesupremacy3
Xtremesupremacy3

Reputation: 65

Python: Converting MySQL datetime to datetime for format

Bit of a newbie here.

I have a program which takes results from a MySQL database. It picks out the fields Id and ship_date, the query searches only for returned records based on a given Id. The results should be 2 or more dates which it does. My aim is to have formatted the dates and compare the days between them. The results are put into separate lists, so I get two lists like this:

[(datetime.datetime(2012, 12, 28, 0, 0),), (datetime.datetime(2012, 12, 28, 0, 0),)]

and

[(datetime.datetime(2012, 06, 15, 0, 0),), (datetime.datetime(2012, 08, 19, 0, 0),)]

for instance.

But when I attempt to turn the whole list into a readable format with a piece of code I found:

ship_date = [dt.strftime("%Y-%m-%d") for dt in ship_date]

I always get an error that there is no attribute strftime. I have tried turning them into strings and then using strftime, but I get the error that str has no attribute strftime. I'm at a complete loss.

Btw, I have imported datetime

Does anyone have any ways I can turn these lists (2 of them) into readable formats like

2012-12-28, 2012-12-28

Thanks

Upvotes: 1

Views: 6386

Answers (1)

falsetru
falsetru

Reputation: 369424

The given list contains tuples with datetime, not just datetime. So the items should be unpacked.

>>> ship_dates = [(datetime.datetime(2012, 12, 28, 0, 0),), (datetime.datetime(2012, 12, 28, 0, 0),)]
>>> [dt.strftime("%Y-%m-%d") for dt in ship_dates]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'strftime'

>>> [dt.strftime("%Y-%m-%d") for (dt,) in ship_dates]
['2012-12-28', '2012-12-28']

Or you can omit (..):

>>> [dt.strftime("%Y-%m-%d") for dt, in ship_dates]
['2012-12-28', '2012-12-28']

Upvotes: 1

Related Questions