0

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?

2 Answers 2

4

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

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

2 Comments

Is there any way I can convert date_object to %Y-%m-%d format, and still have it as a datetime type?
No. A datetime object is not the same thing as a string object.
1

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')

Comments

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.