简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM