Python,将时间戳记字符串转换为MMDDHH整数

时间:2019-01-04 22:13:10

标签: python pandas python-2.7 datetime

我有一个时间戳字符串,例如:

2019-01-04 21:15:00

我想将其转换为MMDDHH形式的整数,四舍五入到最接近的小时数。在这种情况下,结果将是:

10421

首选Python日期时间解决方案,但Pandas也可以。

3 个答案:

答案 0 :(得分:4)

使用round + strftime

pd.to_datetime(s).dt.round('H').dt.strftime('%m%d%H')
Out[249]: 
0    010421
1    010421
2    010421
dtype: object

数据输入

s=pd.Series(['2019-01-04 21:15:00','2019-01-04 21:15:00','2019-01-04 21:15:00'])

答案 1 :(得分:1)

使用datetime库:

import datetime as dt

# Read your string into a datetime object
>>> date_string = dt.datetime.strptime('2019-01-04 21:15:00', '%Y-%m-%d %H:%M:%S')
>>> print date_string
2019-01-04 21:15:00

# Convert it to a different format string
>>> different_date_string = dt.datetime.strftime(date_string, '%m%d%H')
>>> print different_date_string
010421

# Convert it to an integer
>>> print int(different_date_string)
10421

有关舍入的解决方案,请尝试以下功能:

>>> def datestr2int(datestring):
...   d = dt.datetime.strptime(datestring, '%Y-%m-%d %H:%M:%S')
...   if d.minute >= 30:
...     d = d + dt.timedelta(minutes=30)
...   else:
...     pass
...   s = dt.datetime.strftime(d, '%m%d%H')
...   return int(s)
... 
>>> datestr2int('2019-01-04 21:15:00')
10421
>>> datestr2int('2019-01-04 21:30:00')
10422
>>> datestr2int('2019-01-04 23:35:00')
10500

答案 2 :(得分:-1)

看起来已经在StackOverflow上找到了答案。

enter image description here

我尝试过,它对我有用。