Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-日期转换_Python_Datetime - Fatal编程技术网

Python-日期转换

Python-日期转换,python,datetime,Python,Datetime,我正在使用Python,我想将日期转换为以下格式: “2018年9月30日”或“2018年9月30日星期一” 格式如下: '2018-09-30 00:00:00' 我已经尝试过使用strtime()和strftime()函数,但我无法让它们起作用 有人知道如何用Python实现这一点吗 print(datetime.strftime('%Y %m %d %X) 您可以使用strftime更改日期和时间的样式 转到 欲了解更多信息,请使用以下最简单的方法将2018年9月30日或2018年9月

我正在使用Python,我想将日期转换为以下格式:

“2018年9月30日”
“2018年9月30日星期一”

格式如下:

'2018-09-30 00:00:00'

我已经尝试过使用strtime()和strftime()函数,但我无法让它们起作用

有人知道如何用Python实现这一点吗

print(datetime.strftime('%Y %m %d %X)
您可以使用strftime更改日期和时间的样式

转到


欲了解更多信息,请使用以下最简单的方法将2018年9月30日<代码>或2018年9月30日星期一<代码>转换为<代码>2018-09-30 00:00:00,即:


对于相反的转换,有,但我担心它不会输出您想要的序号(1,2),仍然可以使用,即:

def ord(n):

返回str(n)+(“th”如果4您可以使用
datetime.strtime
datetime.strftime
进行类似操作:

from datetime import datetime

def convert1(string):
    conversion = '%d' + string[2:4] + ' %b %Y'
    dt = datetime.strptime(string, conversion)
    return dt.strftime('%Y-%m-%d %H:%M:%S')

def convert2(string):
    conversion = '%a %d' + string[6:8] + ' %b %Y'
    dt = datetime.strptime(string, conversion)
    return dt.strftime('%Y-%m-%d %H:%M:%S')

print(convert1('30th Sep 2018'))
print(convert2('Mon 30th Sep 2018'))

print(convert1('01st Sep 2018'))
print(convert2('Sun 02nd Sep 2018'))
这是输出:

2018-09-30 00:00:00
2018-09-30 00:00:00
2018-09-01 00:00:00
2018-09-02 00:00:00

我使用了所描述的模式。我用于提取日期字符串的
th
部分。在这样做的过程中,我确保函数也适用于
nd
st

到目前为止您尝试了什么?请向我们展示您的代码。@Pedrobito:我使用了strtime()和strftime()函数,但它不起作用。嗨@Debbie,我编辑了你的问题,以便更清楚地说明你在做什么。试着把你已经做的一切都放在StackOverflow和文档上,我真的认为有人已经提出了一个类似于这个问题的问题。@coderade:谢谢编辑。我会记得的你的建议下一次继续。
from datetime import datetime

def convert1(string):
    conversion = '%d' + string[2:4] + ' %b %Y'
    dt = datetime.strptime(string, conversion)
    return dt.strftime('%Y-%m-%d %H:%M:%S')

def convert2(string):
    conversion = '%a %d' + string[6:8] + ' %b %Y'
    dt = datetime.strptime(string, conversion)
    return dt.strftime('%Y-%m-%d %H:%M:%S')

print(convert1('30th Sep 2018'))
print(convert2('Mon 30th Sep 2018'))

print(convert1('01st Sep 2018'))
print(convert2('Sun 02nd Sep 2018'))
2018-09-30 00:00:00
2018-09-30 00:00:00
2018-09-01 00:00:00
2018-09-02 00:00:00