python - 将字符串日期转换为另一个字符串日期

标签 python python-3.x datetime

from datetime import datetime
y='Monday, December 9, 2019'

我想将上面的字符串转换为 DD/MM/YYYY 我尝试过

c=datetime.strptime(y,'%A,%B %-d,%Y')

这样我就可以轻松地转换它,但它给了我ValueError: '-' is a baddirective in format '%A, %B %-d,%Y 我检查了这个问题< br/> '-' is a bad directive in format '%Y-%-m-%-d' - python/django但仍然给出错误,有没有办法在不使用 re 的情况下做到这一点?

最佳答案

正确的格式是'%A, %B %d, %Y'(注意到删除了-),并将其更改为DD/MM/YYYY,格式为%d-%m-%Y'

from datetime import datetime
y='Monday, December 9, 2019'

#Fixed format
c=datetime.strptime(y,'%A, %B %d, %Y')

#Changed to represent DD/MM/YYYY
print(c.strftime('%d-%m-%Y'))

输出将是

09-12-2019

关于python - 将字符串日期转换为另一个字符串日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56638152/

相关文章:

Python - 代码片段不适用于 Python 2.5.6,使用 IDLE

python - 如何在同一标记上连续注册两个点击事件

python - 如何修复: "TypeError: ' bool' object is not subscriptable"

python-3.x - 找到前三个相关类别及其对应的概率

python - 为什么在更改超时变量后,Amazon RDS 上的 MySQL 不断使我的连接超时?

c++ - 日期/时间转换 : string representation to time_t

python - vagrant 和 ubunutu : pip install jupyter error: Storing debug log for failure in/home/vagrant/. pip/pip.log

python - 在同一类中的不同方法创建的对象上调用类中的方法?

ruby-on-rails - Ruby(带 Rails)将一串时间转换成秒?

c# - 如何从另一个日期时间中减去一个日期时间并返回经过的小时数的两倍