[英]Datetime (TypeError: strptime() argument 1 must be str, not Timestamp)
I want add new column 'order_month' from column 'order_date'我想从列“order_date”添加新列“order_month”
The code is:代码是:
import datetime
import pandas as pd
dataset = pd.read_excel("D:\\DataSciencePython/retail_raw_reduced.xltx")
dataset['order_month'] = dataset['order_date'].apply(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d").strftime('%Y-%m'))
print(dataset.head())
The output should be: output 应该是:
order_id order_date customer_id ... quantity item_price order_month
0 1703458 2019-10-17 14004 ... 10 740000 2019-10
1 1706815 2019-10-24 17220 ... 2 604000 2019-10
2 1710718 2019-11-03 16518 ... 8 1045000 2019-11
3 1683592 2019-08-19 16364 ... 4 205000 2019-08
4 1702573 2019-10-16 15696 ... 2 4475000 2019-10
But i found error:但我发现错误:
PS D:\DataSciencePython> & C:/Users/SCZ/AppData/Local/Programs/Python/Python38/python.exe
"d:/DataSciencePython/Data Visualization 1/menambahkolommonth.py"
Traceback (most recent call last):
File "d:/DataSciencePython/Data Visualization 1/menambahkolommonth.py", line 4, in <module>
dataset['order_month'] = dataset['order_date'].apply(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d").strftime('%Y-%m'))
File "C:\Users\SCZ\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\series.py", line 4433, in apply
return SeriesApply(self, func, convert_dtype, args, kwargs).apply()
File "C:\Users\SCZ\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\apply.py", line 1088, in apply
return self.apply_standard()
File "C:\Users\SCZ\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\apply.py", line 1143, in apply_standard
mapped = lib.map_infer(
File "pandas\_libs\lib.pyx", line 2870, in pandas._libs.lib.map_infer
File "d:/DataSciencePython/Data Visualization 1/menambahkolommonth.py", line 4, in <lambda>
dataset['order_month'] = dataset['order_date'].apply(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d").strftime('%Y-%m'))
TypeError: strptime() argument 1 must be str, not Timestamp
Please help me.请帮我。 Thankyou!
谢谢!
Can you run dataset.dtypes
?你可以运行
dataset.dtypes
吗? You can check if order_date
is already a datetime object.您可以检查
order_date
是否已经是日期时间 object。 If it is, then you don't need to datetime.datetime.strptime(x, "%Y-%m-%d")
如果是,那么您不需要
datetime.datetime.strptime(x, "%Y-%m-%d")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.