19

I am trying to write a function in Python 2.7 that converts a series of numbers into a valid date. So far, it all works apart form the conversion.

Here is the relevant code:

import datetime

def convert_date(x,y,z):
    orig_date = datetime.datetime(x,y,z)
    d = datetime.datetime.strptime(str(orig_date), '%Y-%m-%d %H:%M:%S')
    result = d.strftime('%m-%d-%Y')
    return orig_date

a = convert_date(13,11,12)
print a

Whenever I run this, I get:

> Traceback (most recent call last):
>       File "test.py", line 9, in <module>
>         a = convert_date(13,11,12)
>       File "test.py", line 5, in convert_date
>         d = datetime.datetime.strptime(orig_date, '%Y-%m-%d %H:%M:%S')

> TypeError: must be string, not datetime.datetime

I know that this is because strptime gives me a datetime object, but how do I get this to work?

Siong Thye Goh
  • 3,518
  • 10
  • 23
  • 31
Fake Name
  • 813
  • 2
  • 9
  • 17
  • 3
    Get rid of the `except: pass` and you'll see what's wrong. This is exactly why `except:pass` is never a good idea, when you want to pass on an exception you should specify which exception. – Kos May 07 '16 at 20:40
  • Thanks, I get AttributeError: `'module' object has no attribute 'strptime'` – Fake Name May 07 '16 at 20:45

1 Answers1

30

For anyone who runs into this problem in the future I figured I might as well explain how I got this working.

Here is my code:

from datetime import datetime

def convert_date(x,y,z):
    orig_date = datetime(x,y,z)
    orig_date = str(orig_date)
    d = datetime.strptime(orig_date, '%Y-%m-%d %H:%M:%S')
    d = d.strftime('%m/%d/%y')
    return d

As I should have figured out from the error message before I posted, I just needed to convert orig_date to a string before using strftime.

Aashish Chaubey
  • 589
  • 1
  • 8
  • 22
Fake Name
  • 813
  • 2
  • 9
  • 17