简体   繁体   English

在Python中将字符串转换为日期格式

[英]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): 我编写了以下代码,将其转换为所需的日期格式(上面的字符串作为参数传递给covertDate函数):

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 : 您将返回date_correct_form ,这是strftime的结果:

Return a string representing the date , controlled by an explicit format string. 返回表示日期的字符串 ,由明确的格式字符串控制。

(emphasis mine) (强调我的)

If you want the datetime object, return date_object . 如果要使用datetime对象,请返回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 现在,您已经在date_string拥有了已格式化的字符串,并且如果您仍然需要对datetime对象执行逻辑,那就是date_obj

You can use easy_date to make it easy: 您可以使用easy_date使其变得容易:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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