【问题标题】:ValueError in dataframe while trying to extract day, month and year using datetime python library尝试使用日期时间python库提取日、月和年时数据框中的ValueError
【发布时间】:2020-09-16 09:31:18
【问题描述】:

我的数据框中包含三列:推文发布时间 (UTC)、推文内容和推文位置。 “Tweet Posted Time (UTC)”列的日期对象格式为:31 Mar 2020 10:49:01

我的目标是重新格式化数据框,使“Tweet Posted Time (UTC)”列仅显示日、月和年(例如 2020 年 3 月 31 日),以便能够绘制时间序列图,但我的尝试导致以下错误。

ValueError: 时间数据 '0 2020 年 3 月 31 日 10:49:01\n1 2020 年 3 月 31 日 05:48:43\n2 2020 年 3 月 30 日 05:38:50\n3 2020 年 3 月 29 日 21:19:23\n4 29 2020 年 3 月 20:28:22\n ... \n2488 2018 年 1 月 2 日 13:36:07\n2489 2018 年 1 月 2 日 10:33:21\n2490 2018 年 1 月 1 日 12:23:47\n2491 2018 年 1 月 1 日 06:03 :51\n2492 2018 年 1 月 1 日 02:09:15\n名称:推文发布时间 (UTC),长度:2451,dtype: object' 与格式 '%d %b %Y %H:%M:%S' 不匹配

我的代码在下面,请你告诉我我做错了什么吗?

from datetime import datetime
import pandas as pd
import re #regular expression
from textblob import TextBlob
import string
import preprocessor as p


pd.set_option("expand_frame_repr", False)

df1 = pd.read_csv("C:/tweet_data.csv")

dataType = df1.dtypes
print(dataType)

# convert datetime object to string
old_formatDate = str(df1['Tweet Posted Time (UTC)'])

# extract day, month, and year and convert back to datetime object
date_TimeObject = datetime.strptime(old_formatDate, '%d %b %Y %H:%M:%S')
new_formatDate = date_TimeObject.strftime('%d-%m-%Y')
print(new_formatDate)

【问题讨论】:

    标签: python twitter nlp


    【解决方案1】:

    我通过将数据框更改为熊猫系列然后更改为日期时间格式来研究并解决了这个问题。然后,应用 dt.strftime。

    df.columns = ['Tweet_Posted_Time', 'Tweet_Content', 'Tweet_Location']
    print(df)
    
    # Convert the date and time column (Tweet_Posted_Time) from panda data frame to Panda Series
    df1 = pd.Series(df['Tweet_Posted_Time'])
    print(df1)
    
    # Convert the Panda Series to datetime format
    df1 = pd.to_datetime(df1)
    print(df1)
    
    # convert the date column to new date format
    df1 = df1.dt.strftime('%d-%m-%Y')
    print(df1)
    
    # Replace the Column "Tweet_Posted_Time" in the original data frame with the new data frame containing new date format
    df.assign(Tweet_Posted_Time=df1)````
    

    【讨论】:

      猜你喜欢
      • 2016-07-27
      • 2019-10-14
      • 1970-01-01
      • 2017-10-17
      • 2019-02-20
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 2020-08-18
      相关资源
      最近更新 更多