python - 将相对时间更改为 pandas 数据框中的实际日期

标签 python pandas datetime dataframe

我目前有一个通过抓取谷歌新闻头条创建的数据框。我的专栏之一是“时间”,指的是一篇文章的发表时间。

不幸的是,对于最近的文章,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_datetimeto_timedelta首先然后使用combine_firstfloor :

#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/

相关文章:

python - collat​​z 算法,当输入长度至少为 (n) 时返回第一个整数

python - 查找执行中的python程序路径

python - Pandas 的 rolling_mean 不稳定性

python - 创建列的内存高效方法,该列指示来自一组列的值的唯一组合

datetime - 如何使用 GnuPlot 从存储在单独列中的 CSV 文件日期和时间绘制时间序列图表?

wpf - 如何使用 Bindings 获取 DateTime 值? (WPF-MVVM)

python - 在不知道路径的情况下使用 python 查找图像列表(可能是 .jpg)。

python - 在 Mac 上更新 Python

python - numpy 的 ones_like 的 pandas 版本

Java - 解析带有可选秒的日期