我目前有一个通过抓取谷歌新闻头条创建的数据框。我的专栏之一是“时间”,指的是一篇文章的发表时间。
不幸的是,对于最近的文章,Google 新闻使用“相对”日期,例如 6 小时前或 1 天前,而不是 2017 年 11 月 1 日。
我真的很想将这些相对日期转换为与其他条目一致(例如,他们也说 2017 年 11 月 12 日),但我不知道从哪里开始。
我的想法是创建一个代表今天日期的变量,然后通过数据帧进行某种搜索以查找与我的格式不匹配的内容,然后用当前日期减去这些相对时间。我还必须对“几小时前”的内容进行某种过滤器,并且只让它们等于当前日期。
我并不是真的想要一个解决方案,而是想要一个大概的想法来尝试解决这个问题。我应该尝试使用 numpy 吗?
一些行的示例:
Publication Time Headline
0 The San Diego Union-Tribune 6 hours ago I am not opposed to new therapeutic modalities...
1 Devon Live 13 hours ago If you're looking for a bargain this Christmas...
15 ABS-CBN News 1 day ago Now, Thirdy has a chance to do something that ...
26 New York Times Nov 2, 2017 Shepherds lead their sheep through the centre ...
最佳答案
您可以使用to_datetime
与 to_timedelta
首先然后使用combine_first
与 floor
:
#create dates
dates = pd.to_datetime(df['Time'], errors='coerce')
#create times
times = pd.to_timedelta(df['Time'].str.extract('(.*)\s+ago', expand=False))
#combine final datetimes
df['Time'] = (pd.datetime.now() - times).combine_first(dates).dt.floor('D')
print (df)
Publication Time \
0 The San Diego Union-Tribune 2017-11-12
1 Devon Live 2017-11-11
2 ABS-CBN News 2017-11-11
3 New York Times 2017-11-02
Headline
0 I am not opposed to new therapeutic modalities
1 If you're looking for a bargain this Christmas
2 Now, Thirdy has a chance to do something that
3 Shepherds lead their sheep through the centre
print (df['Time'])
0 2017-11-12
1 2017-11-11
2 2017-11-11
3 2017-11-02
Name: Time, dtype: datetime64[ns]
关于python - 将相对时间更改为 pandas 数据框中的实际日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47246143/