26

I have a problem with the following code. I get an error "strptime() argument 1 must be str, not Timestamp"

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

2
  • Looks like Python. Please use Edit and add a language-specific tag. Commented May 1, 2019 at 19:42
  • Yes, it is Python. Thank you for the advice! Commented May 1, 2019 at 19:44

5 Answers 5

23

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') 
Sign up to request clarification or add additional context in comments.

1 Comment

I did not think it could work but it does! Thank you a lot
10

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:

date_time_obj = date.to_pydatetime()

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

Comments

9

If the object is a Python Timestamp, you can implement:

timestamp = Timestamp('2017-11-12 00:00:00')

str_timestamp = str(timestamp)

2 Comments

This is a duplicate of this other answer. Please don't post duplicate answers. See How to Answer for more information.
Downvoted because: 1/ there is no such thing as a "Python Timestamp". There is a pandas.Timestamp, though. 2/ This answer is incomplete: a) it doesn't take its input from OP's code (it should be date, not '2017-11-12 00:00:00'). b) the resulting str_timestamp cannot be used as-is in OP's code, it needs to be converted to a datetime, as shown in the anwser linked in the comment above mine. It could be improved by showing that date (which is a pandas.Timestamp) can be used directly instead of converting it to string then datetime: pandas.Timestamp also has a time() and date() methods.
2

Just adding to the above answers as ran into the following probem using the solutions provided:

AttributeError: module 'datetime' has no attribute 'strptime'

Based on the answer found here, you need to either coerce the timestamp into a string like this:

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

Or make sure to import the class and not just the module like this:

from datetime import datetime

Comments

1
import pandas as pd
import datetime

base = pd.to_datetime("2022-10-10")
date_list = [datetime.datetime.strftime(pd.to_datetime(base - datetime.timedelta(days=x)),"%Y-%m-%d") for x in range(7)]
print(date_list)

output will be

['2022-10-10',
 '2022-10-09',
 '2022-10-08',
 '2022-10-07',
 '2022-10-06',
 '2022-10-05',
 '2022-10-04']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.