pandas 如何在Python中将时间戳转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/55941595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert timestamp into string in Python
提问by Rachele Povelato
I have a problem with the following code. I get an error "strptime() argument 1 must be str, not Timestamp"
我对以下代码有问题。我收到错误消息“strptime() 参数 1 必须是 str,而不是时间戳”
I guess that what I should do is to convert date from timestamp to string but I do not know what to do.
我想我应该做的是将日期从时间戳转换为字符串,但我不知道该怎么做。
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)
I get the error in
我得到了错误
date_time_obj = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
How can I solve this prolem? Thank you in advance
我该如何解决这个问题?先感谢您
采纳答案by Paul Wildenhain
Can you coerce the data type to a string to perform this calculation?
您能否将数据类型强制转换为字符串以执行此计算?
date_time_obj = datetime.strptime(str(date), '%Y-%m-%d %H:%M:%S')
回答by adrtam
If it says "strptime() argument 1 must be str, not Timestamp", likely that you already have the pandas.Timestamp
object, i.e., it is not a string but a parsed date time, only it is in Pandas' format, not Python's. So to convert, use this:
如果它说“strptime() 参数 1 必须是 str,而不是时间戳”,则可能您已经拥有该pandas.Timestamp
对象,即它不是字符串而是解析的日期时间,只是它采用 Pandas 的格式,而不是 Python 的格式。所以要转换,使用这个:
date_time_obj = date.to_pydatetime()
instead of date_time_obj = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
代替 date_time_obj = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')