python - 日期时间格式 Python 中的日期字符串
问题描述
这是我无法解决的错误
ValueError: time data '1/31/2021 22:59' does not match format '%d/%m/%Y %H:%M:%S'
这是我的代码 90% 的时间我需要转换的字符串日期在我的try
部分中并且它有效,我的第二部分有问题。
def StringToDateTime(DateString):
from datetime import datetime
try:
return datetime.strptime(DateString, '%Y-%m-%d %H:%M:%S')
except:
DateString = str(DateString)+':00'
return datetime.strptime(DateString, '%d/%m/%Y %H:%M:%S')
解决方案
您看到的错误是由于str
没有秒值 -%S
日期时间格式字符串的。
更改格式字符串,使其没有秒占位符,它应该按预期工作:
try:
# Remove the %S from the format string here
return datetime.strptime(DateString, '%Y-%m-%d %H:%M')
except:
DateString = str(DateString)+':00'
return datetime.strptime(DateString, '%d/%m/%Y %H:%M:%S')
或者,如果你想改变DateString
你在你的except
条款中所做的:
# Add the seconds to the date string
DateString = f"{DateString}:00"
try:
return datetime.strptime(DateString, '%Y-%m-%d %H:%M:%S')
except:
return datetime.strptime(DateString, '%d/%m/%Y %H:%M:%S')
推荐阅读
- unity3d - 用另一个对撞机或游戏对象切割或遮盖游戏对象
- math.js - math.sec(x) 不适用于 android,但适用于 codepen
- android - Flutter:如何在 Flutter 2.5.3 中获取 device_id 和 device_token?
- ios - Alamofire 的 Session timeOutInterval 和 cachePolicy 设置未反映在 URLRequest 上
- c# - Jobject 在嵌套元素中使用 .Add
- javascript - Mapping and displaying Fontawesome Icons
- spring - 带有会话复制的 Jetty Spring Boot
- php - 如何使用 curl php 与 monday.com 连接以在 monday.com 中创建潜在客户或交易?
- java - 使用 GSON 解析 JSON 会忽略字段对象
- c# - 问题更新到 .Net 6 - 加密字符串