如何在Python中使用strptime将包含字符的字符串转换为日期时间

huangapple go评论115阅读模式
英文:

how to convert a string containing characters into date time using strptime in Python

问题

from datetime import datetime
datetime.strptime(x, "%Y%m%d%H%M")
ValueError: unconverted data remains: A1745
英文:

I'm trying to convert a string where there exists a characters between date information into a datetime. I was wondering if this is possible without using replace function. Suppose my string is defined as '20220117A1745' implying Jan. 17th, 2022 at 5:45pm.

If I use strptime, as expected, I receive an error.

from datetime import datetime
datetime.strptime(x,"%Y%m%d%H%M")
ValueError: unconverted data remains: A1745

I was wondering if I can do this without using another method. The reason why I don't want to use antoher method is that, replace has a bad time ecomplexity and will slow the execution time badly (see for reference). I'll do this operation for hundreds of thousans of strings in a for loop.

答案1

得分: 1

以下是翻译好的内容:

from datetime import datetime

x = '20220117A1745'
date_str = x[:8] + x[9:]
date_obj = datetime.strptime(date_str, '%Y%m%d%H%M')
print(date_obj)

输出结果为:

2022-01-17 17:45:00
英文:

What about

from datetime import datetime

x = '20220117A1745'
date_str = x[:8] + x[9:]
date_obj = datetime.strptime(date_str, '%Y%m%d%H%M')
print(date_obj)

which gives

2022-01-17 17:45:00

答案2

得分: 1

如果字符串始终在相同位置包含'A',则可以这样做:

from datetime import datetime
x = '20220117A1745'
print(datetime.strptime(x, "%Y%m%dA%H%M"))

如果不知道字母是什么:

print(datetime.strptime(x[:8]+x[9:], "%Y%m%d%H%M"))

两种方法的输出结果:

2022-01-17 17:45:00

英文:

If the string always has 'A' in the same position then you can do this:

from datetime import datetime
x = '20220117A1745'
print(datetime.strptime(x,"%Y%m%dA%H%M"))

If you don't know what the letter is then:

print(datetime.strptime(x[:8]+x[9:],"%Y%m%d%H%M"))

Output for both methods:

2022-01-17 17:45:00

huangapple
  • 本文由 发表于 2023年2月24日 00:15:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547449.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定