python-3.x 如何将时间格式不正确的字符串转换为时间戳?

bf1o4zei  于 2023-04-22  发布在  Python
关注(0)|答案(1)|浏览(103)
str1='gio lug  7 00:36:20 CEST 2022'

str2='Wed Nov 17 12:43:56 zzz 2021'

str3='mi� nov 24 09:44:53 WET 2021'

str4='mer. sept. 23 11:58:21 CEST 2020'

我想把这个字符串转换成时间戳,可以吗?
我试过这个:

from dateutil import parser

from datetime import datetime

i= 'gio lug  7 00:36:20 CEST 2022'

dt = parser.parse(i)

print(dt)

a=datetime.strftime(dt,'%Y-%m-%d %H:%M:%S')

print(a)

但它给出错误像:x1c 0d1x
预期格式为(' %Y-%m-%d %H:%M:%S')

qyswt5oh

qyswt5oh1#

这里有几个问题。首先,您的日期没有采用特定的格式,您使用不同的语言来表示星期几和月份。编号也不一致,有时您在星期和月份之后使用.mi�并不意味着任何东西。您必须具有一致的格式或将不同的格式Map到不同的字符串。有关详细信息,请访问https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime
看看这个例子:

from datetime import datetime

import locale
#setting locale to Italian (gio, lug) is Giovedi Luglio I suppose...
locale.setlocale(locale.LC_ALL, 'it_IT.UTF-8')

str1='gio lug 07 00:36:20 CEST 2022' #changed lug 7 to lug 07 to have 2 digits day
str2='Wed Nov 17 12:43:56 zzz 2021'
str3='mi� nov 24 09:44:53 WET 2021'
str4='mer. sept. 23 11:58:21 CEST 2020'

dates = [str1, str2, str3, str4]
for date_string in dates:
    try:
        date_string = date_string.replace(".", "") #removing dots
        date = datetime.strptime(date_string, "%a %b %d %H:%M:%S %Z %Y")
        print(date)
    except Exception as e:
        print(e)

输出如下:

2022-07-07 00:36:20  #good, it matches!
time data 'Wed Nov 17 12:43:56 zzz 2021' does not match format '%a %b %d %H:%M:%S %Z %Y'  #this is not Italian anymore, so it doesn't match
time data 'mi� nov 24 09:44:53 WET 2021' does not match format '%a %b %d %H:%M:%S %Z %Y'  #mi� is invalid, it doesn't match
time data 'mer sept 23 11:58:21 CEST 2020' does not match format '%a %b %d %H:%M:%S %Z %Y'  #mer is Italian (Mercoledi?) and Sept is English.. so again, doesn't match

相关问题