python - 如何在Python中将时间戳转换为字符串

标签 python pandas strptime

我的以下代码有问题。我收到错误“strptime() 参数 1 必须是 str,而不是时间戳”

我想我应该做的是将日期从时间戳转换为字符串,但我不知道该怎么做。

class TweetAnalyzer:

    def tweets_to_data_frame(self,ElonMuskTweets):

        df = pd.DataFrame(data=[tweet.text for tweet in ElonMuskTweets],columns=['Tweets'])

        df['Text length'] = np.array ([len(tweet.text)for tweet in ElonMuskTweets])
        df['Date and time of creation'] = np.array ([tweet.created_at for tweet in ElonMuskTweets])
        df['Likes'] = np.array ([tweet.favorite_count for tweet in ElonMuskTweets])
        df['Retweets'] = np.array ([tweet.retweet_count for tweet in ElonMuskTweets])

        list_of_dates = []   
        list_of_times = []

        for date in df['Date and time of creation']:

            date_time_obj = datetime.strptime(date, '%Y-%m-%d %H:%M:%S') 
            list_of_dates.append(date_time_obj.date())  
            list_of_times.append(date_time_obj.time())

            df['Date'] = list_of_dates
            df['Time'] = list_of_times

            df['Date'] = pd.to_datetime(df['Date'])

            start_date = '2018-04-13'
            end_date = '2019-04-13'

            mask1 = (df['Date'] >= start_date) & (df['Date'] <= end_date)
            MuskTweets18_19 = df.loc[mask1]  

            return MuskTweets18_19.to_csv ('elonmusk_tweets.csv',index=False)

我收到错误

date_time_obj = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')

如何解决这个问题? 预先感谢您

最佳答案

您可以将数据类型强制转换为字符串来执行此计算吗?

date_time_obj = datetime.strptime(str(date), '%Y-%m-%d %H:%M:%S') 

关于python - 如何在Python中将时间戳转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55941595/

相关文章:

Python smtplib 代理支持

python - 如何计算 Pandas 数据框中的结果行?

python - 如何将一列的不同行与 pandas 中的 Levenshtein 距离度量进行比较?

python - 如何从包含特定列中特定字符串的 Pandas 数据框中删除行?

sorting - 可排序、可读且标准的日志时间格式

python - 如何修改 QDataWidgetMapper 的值

python - 当索引超出范围时如何再次循环列表

python - Pandas Dataframe 中两个日期之间的营业时间(包括节假日)

python - 更快的 strptime?

python - ISO 时间到 python 中的人类可读时间