Converting String to Date Format in Python

I have the following date I need to convert:

Wed, 09 Jul 2014 12:22:17 +0000

This is currently stored as a String. I wrote this code to convert it to the date format I want (the String above is passed as an argument to the covertDate function):

def convertDate(dictValue):

    date_string = dictValue
    format_string = '%a, %d %b %Y %H:%M:%S %z'
    date_object = datetime.datetime.strptime(date_string, format_string)
    date_correct_form = date_object.strftime("%Y-%m-%d")
    print(type(date_correct_form))
    print(date_correct_form)

    return date_correct_form

The output is as follows:

<class 'str'>
2014-10-30

I get the format that I want, but it still isn't recognized as a date.

How can I make it so?

Upvotes: 0

Views: 118

Answers (2)

Raphael Amoedo
Raphael Amoedo

Reputation: 4455

You can use easy_date to make it easy:

import date_converter
converted_date = date_converter.string_to_date(date_string, '%a, %d %b %Y %H:%M:%S %z')

Upvotes: 1

Andy
Andy

Reputation: 50540

You are returning date_correct_form, which is the result of strftime:

Return a string representing the date, controlled by an explicit format string.

(emphasis mine)

If you want the datetime object, return date_object. If you need both, you can return both:

return date_correct_form, date_object

You can call it like so:

date_string, date_obj = convertDate(dictValue)

You now have the already formatted string in date_string, and if you still need to do logic against the datetime object, that is in date_obj

Upvotes: 4

Related Questions