TypeError: strptime() argument 1 must be str, not list
As the other answers suggest, you require a different way, probably map
. You may also use pd.to_datetime()
and pass it the whole list. And then use the same as x-axis and the wind_speed for y-axis.
import pandas as pd
timestamp = pd.to_datetime(T[1:])
It will create a DatetimeIndex which you can again format according to your needs, like:
timestamp = timestamp.strftime("%Y%m%d %I:%M:%S")
In one line:
timestamp = pd.to_datetime(T[1:]).strftime("%Y%m%d %I:%M:%S")
After having two lists for timestamp and wind_speed, use may use something like:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(13,6))
ax.plot(timestamp, wind_speed)
plt.xticks(rotation=30)
plt.show()
datetime to string with series in pandas
There is no .str
accessor for datetimes and you can't do .astype(str)
either.
Instead, use .dt.strftime
:
>>> series = pd.Series(['20010101', '20010331'])
>>> dates = pd.to_datetime(series, format='%Y%m%d')
>>> dates.dt.strftime('%Y-%m-%d')
0 2001-01-01
1 2001-03-31
dtype: object
See the docs on customizing date string formats here: strftime() and strptime() Behavior.
For old pandas versions <0.17.0
, one can instead can call .apply
with the Python standard library's datetime.strftime
:
>>> dates.apply(lambda x: x.strftime('%Y-%m-%d'))
0 2001-01-01
1 2001-03-31
dtype: object
strptime() argument 1 must be str, not Series
you are getting startTime
in string, so lets first convert that to datetime objects.
import pandas as pd
import requests
historical = requests.get(
'https://ftx.com/api/markets/usdt-perp/candles?resolution=14400&start_time=1309062800').json()
historical = pd.DataFrame(historical['result'])
historical['startTime'] = pd.to_datetime(
historical['startTime']).dt.strftime('%d/%m/%y %H')
print(historical)
response : strptime() argument 1 must be str, not datetime.datetime django datetime format problem
strptime
takes a string and converts it to a datetime.datetime
object. You should not have passed a datetime.datetime
to it.
datetime.datetime.strptime("2021-02-19", "%Y-%m-%d")
datetime.datetime(2021, 2, 19, 0, 0)
If you need to convert a datetime.datetime
to a string, use strftime
:
mytime = datetime.datetime(2022, 2, 19, 14, 23, 51)
mytime.strftime('%Y-%m-%dT%H:%M:%SZ')
'2022-02-19T14:23:51Z'
TypeError : strptime() argument 1 must be str, not None
The unittest has worked correctly in your code - it indicates your try/except is not capturing the correct exception. Change your exception to TypeError
and it will be caught and the message returned.
You should use self.assertRaisesMesssage
if your aim is to check the expected error and error message that passing in None
as arg1 produces.
mock_val = None
parameter_name = 'Foo'
date_format_info = 'YYYY/MM/DD HH:mm:ss'
expected_msg = f"Invalid value {mock_val} of parameter {parameter_name}. {parameter_name.capitalize()} should be at format '{date_format_info}'"
with self.assertRaisesMessage(TypeError, expected_msg):
validate_date(self.logger, mock_val, parameter_name, '%Y/%m/%d %H:%M:%S', date_format_info)
TypeError: strptime() argument 1 must be str, not Period
If you take the year through the dt
acessor of timeseries, you get integers (instead of "Period" objects):
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s')
df['timestamp'] = df['timestamp'].dt.year
y1 = df['timestamp'].iloc[0]
y2 = df['timestamp'].iloc[1]
# d1 = datetime.strptime(y1, "%Y") <- No need to recast to datetime!
# d2 = datetime.strptime(y2, "%Y")
diff = abs((y2 - y1))
print(diff)
>>> 14
As you see, I commented the two lines were you were trying to recast the years into datetime
objects. Was there a reason for this? From your question, I assumed you wanted the difference in number of years. If you wanted the exact number of days between the timestamps then this should do: (no need to cast and recast):
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s')
y1 = df['timestamp'].iloc[0]
y2 = df['timestamp'].iloc[1]
diff = abs((y2 - y1).days)
print(diff)
>>> 5122
strptime() argument 1 must be str, not Series time series convert
You can do it in two ways:
Method 1:
Here we pass a string to the function using map
list(map(lambda x: datetime.datetime.strptime(x,'%b %d, %Y').strftime('%m/%d/%Y'), old_df['oldDate']))
Method 2:
Here we pass a series
pd.to_datetime(old_df['oldDate'], format='%b %d, %Y')
TypeError: strptime() argument 1 must be str, not datetime.datetime in tweepy
tweet.created_at should be a datetime object already, so if you want to format to string, datetime.strftime(tweet.created_at, '%Y-%m-%dT%H:%M:%SZ')
TypeError: strptime() argument 1 must be str, not Series
You need to apply this conversion operation for every row item of your DataFrame, therefore use df.apply
function e.g. to create a new pd.Series
object and then assign it to the needed column.
df['inward_date'] = df['inward_date'].apply(lambda x: datetime.strptime(x[:10], "%Y-%m-%d").strftime("%d-%m-%Y"))
Related Topics
How to Check Whether All Elements of Array Are in Between Two Values
Dividing Each Row by the Previous One
Importerror: No Module Named Psycopg2 After Install
Why Does Tkinter Image Not Show Up If Created in a Function
Convert Np.Array of Type Float64 to Type Uint8 Scaling Values
Numpy Distance Calculations of Different Shaped Arrays
How to Drop Rows of Pandas Dataframe Whose Value in a Certain Column Is Nan
How to Replace Negative Numbers in Pandas Data Frame by Zero
How to Tell If Tensorflow Is Using Gpu Acceleration from Inside Python Shell
Pip Install Not Working With Jenkins
How to Read Pdf Files One by One from a Folder in Python
Looping in Python: Modify One Column Based on Values in Other Columns
Importing Large Tab-Delimited .Txt File into Python
Defining and Calling a Function Within a Python Class
Better Way to Extract Only 2Nd Column of a Txt File in Python
Output the Same Amount of Rows as Asterisks Using For-Loop
Python Data Frame How to Find the Local Maximum in a 2D Array