问题描述
我想将y-m-dTh:m
格式为datetime
的字符串转换为python datetime
对象。我运行以下代码:
>>> import datetime
>>> datetime.datetime.strptime('2020-09-02T22:05',"%Y-%m-%dT%H:%M%f")
我的预期输出是:
datetime.datetime(2020,9,2,22,5,0)
datetime.datetime(2020,500000)
我的代码有什么问题?
解决方法
如果您运行的是Python 3.7或更高版本,请使用func downloadAllImages(imageUrls: [String]) {
var imageUrls = imageUrls
if imageUrls.count > 0 {
getResult(url: imageUrls[0]) { (data) in
// Now you are in the Main thread
// here data is the output got the output
imageUrls.remove(at: 0)// remove the down element
downloadAllImages(imageUrls: imageUrls) // Again call the next one
}
}
}
:
fromisoformat
- 易于使用,efficient。
问题在于,使用%M%f
时,它试图将05
部分解析为分钟数,然后是微秒数。
当用于输出(与strftime
一起使用时,%M
和其他各个字段应始终产生两位数的值,而%f
应该即使前导零也总是产生一个6位数的值,因此,例如,
dt.strftime('%Y-%m-%dT%H:%M:%S.%f')
(其中dt
是日期时间对象),您可能会得到类似以下内容的信息:
2020-01-01T00:00:00.000000
但是,在输入(带有strptime
)上,它的设计目的是宽大处理分钟数少于1位数且少于6位数的字符串-与其他领域类似。在字符串和格式说明符的秒数之后插入小数点可能是最容易看到的。这两个:
datetime.datetime.strptime('2020-1-2T3:4:5.6','%Y-%m-%dT%H:%M:%S.%f')
datetime.datetime.strptime('2020-01-02T03:04:05.600000','%Y-%m-%dT%H:%M:%S.%f')
给出相同的输出:
datetime.datetime(2020,1,2,3,4,5,600000)
在您的情况下,您没有任何分隔符,例如小数点(实际上,您同时具有分钟和微秒,但没有秒,这可能没有用),但是它仍然会尽力匹配字符串格式说明符,而不是给出错误。因此,它用分钟来标识0
,用微秒的最高有效十进制数字来标识5
,因此就是您所看到的输出。
这里的解决方案只是忽略%f
。
>>> datetime.datetime.strptime('2020-09-02T22:05','%Y-%m-%dT%H:%M')
datetime.datetime(2020,9,22,5)