python-3.x - 如何使用python将字符串日期时间转换为int

标签 python-3.x pandas datetime

我正在做数据预处理,所以我尝试将日期字符串格式转换为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%b12%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/

相关文章:

python - Python 3 和 Python 2 之间 type() 和 hasattr() 的区别

python-3.x - Rodeo UnicodeDecodeError : 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)

python - 如何从 pandas 数据集中创建网格大小不均匀的热图?

python - 来自 pandas.HDFStore 的 HDF 表的奇怪布局

python - 如何在 Python 中将 CSV 文件的 UTC 转换为 CEST

python-3.x - Pandas 选择无法转换为 int 或 float 的行

python - 部署到Google云函数: Error message: 'main'

python - Pandas :根据另一列的映射值创建新列

mysql - 从 MySQL/数据库获取 DateTime 中的 -0200

datetime - foo.Seconds()(类型为time.Duration)错误-无法将'd.Step.Seconds()'(类型为float64)用作time.Duration类型