我正在做数据预处理,所以我尝试将日期字符串格式转换为int,但出现错误,请帮助我如何转换。
我有这样的数据:
0 Apr-12
1 Apr-12
2 Mar-12
3 Apr-12
4 Apr-12
我尝试过这个:
d=df['d_date'].apply(lambda x: datetime.strptime(x, '%m%Y'))
我收到一个错误。
ValueError Traceback (most recent call last)
<ipython-input-134-173081812744> in <module>()
----> 1 d=test['first_payment_date'].apply(lambda x: datetime.strptime(x, '%m%Y'))
~\Anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
4036 else:
4037 values = self.astype(object).values
-> 4038 mapped = lib.map_infer(values, f, convert=convert_dtype)
4039
4040 if len(mapped) and isinstance(mapped[0], Series):
pandas\_libs\lib.pyx in pandas._libs.lib.map_infer()
<ipython-input-134-173081812744> in <lambda>(x)
----> 1 d=test['first_payment_date'].apply(lambda x: datetime.strptime(x, '%m%Y'))
~\Anaconda3\lib\_strptime.py in _strptime_datetime(cls, data_string, format)
563 """Return a class cls instance based on the input string and the
564 format string."""
--> 565 tt, fraction = _strptime(data_string, format)
566 tzname, gmtoff = tt[-2:]
567 args = tt[:6] + (fraction,)
~\Anaconda3\lib\_strptime.py in _strptime(data_string, format)
360 if not found:
361 raise ValueError("time data %r does not match format %r" %
--> 362 (data_string, format))
363 if len(data_string) != found.end():
364 raise ValueError("unconverted data remains: %s" %
ValueError: time data 'Apr12' does not match format '%m%Y'
最佳答案
IIUC,您需要设置%b-%y
,因为Apr
是%b
,12
是%y
。引用Python's strftime directives了解更多信息。转换为日期时间对象后,您可以将它们转换为 UNIX。
df:
col
0 Apr-12
1 Apr-12
对于 int 日期时间,
pd.Series(pd.to_datetime(df['col'], format='%b-%y').values.astype(float)).div(10**9)
输出:
0 1.333238e+09
1 1.333238e+09
dtype: float64
说明:
pd.to_datetime(df['col'], format='%b-%y')
输出:
0 2012-04-01
1 2012-04-01
Name: col, dtype: datetime64[ns]
关于python-3.x - 如何使用python将字符串日期时间转换为int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57613595/