0

我正在尝试从https://finansial.bisnis.com/read/20210506/90/1391096/laba-bank-mega-tumbuh-dua-digit-kuartal-i-2021-ini-penopangnya. 我正在尝试抓取新闻的日期,这是我的代码:

news['tanggal'] = newsScrape['date']
dates = []
for x in news['tanggal']:
    x = listToString(x)
    x = x.strip()
    x = x.replace('\r', '').replace('\n', '').replace(' \xa0|\xa0', ',').replace('|', ', ')
    dates.append(x)
dates = listToString(dates)
dates = dates[0:20]
if len(dates) == 0:
    continue
news['tanggal'] = dt.datetime.strptime(dates, '%d %B %Y, %H:%M')

但我收到了这个错误:

ValueError: time data '06 Mei 2021, 11:32  ' does not match format '%d %B %Y, %H:%M'

我的假设是因为Mei是印度尼西亚语,同时格式需要May是英语。怎么变MeiMay?我已经尝试过dates = dates.replace('Mei', 'May'),但它对我不起作用。当我尝试它时,我得到了错误ValueError: unconverted data remains: 日期的类型是string。谢谢

4

3 回答 3

0

您对 May -> Mei 更改的假设是正确的,替换后您可能会遇到问题的原因是您的字符串中的尾随空格,这在您的格式中没有考虑。您可以使用string.rstrip()删除这些空格。

import datetime as dt

dates = "06 Mei 2021, 11:32  "
dates = dates.replace("Mei", "May") # The replacement will have to be handled for all months, this is only an example
dates = dates.rstrip()
date = dt.datetime.strptime(dates, "%d %B %Y, %H:%M")
print(date) # 2021-05-06 11:32:00

虽然这确实解决了这里的问题,但在dates = dates[0:20]. 考虑使用正则表达式一次获得适当的格式。

于 2021-05-06T05:33:32.820 回答
0

问题似乎只是您拥有的尾随空格,它解释了错误ValueError: unconverted data remains: 。它抱怨它无法转换剩余的数据(空白)。

s = '06 Mei 2021, 11:32  '.replace('Mei', 'May').strip()
datetime.strptime(s, '%d %B %Y, %H:%M')
# Returns datetime.datetime(2021, 5, 6, 11, 32)

此外,要将所有印度尼西亚月份转换为英语,您可以使用字典:

id_en_dict = {
    ...,
    'Mei': 'May',
    ...
}
于 2021-05-06T05:33:44.563 回答
0

您可以尝试以下方法

import datetime as dt
import requests
from bs4 import BeautifulSoup
import urllib.request

url="https://finansial.bisnis.com/read/20210506/90/1391096/laba-bank-mega-tumbuh-dua-digit-kuartal-i-2021-ini-penopangnya"
r = requests.get(url, verify=False)
soup = BeautifulSoup(r.content, 'html.parser')
info_soup= soup.find(class_="new-description")
x=info_soup.find('span').get_text(strip=True)
x = x.strip()
x = x.replace('\r', '').replace('\n', '').replace(' \xa0|\xa0', ',').replace('|', ', ')
x = x[0:20]
x = x.rstrip()
date= dt.datetime.strptime(x.replace('Mei', 'May'), '%d %B %Y, %H:%M')
print(date)

结果:

2021-05-06 11:45:00
于 2021-05-06T05:42:05.903 回答