【问题标题】:Python, convert timestamp string to MMDDHH integerPython,将时间戳字符串转换为 MMDDHH 整数
【发布时间】:2019-05-31 11:50:04
【问题描述】:

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

2019-01-04 21:15:00

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

10421

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

【问题讨论】:

  • 你需要四舍五入不是吗?
  • Yes.... 看起来接受的答案已被修改。保留接受的答案,以便在 Pandas 上使用 datetime,并转换为整数。
  • 如果你更喜欢python,下次可以去掉pandas标签。

标签: python pandas python-2.7 datetime


【解决方案1】:

看起来这在 StackOverflow 上已经有了答案..

Converting a datetime object to an integer python

我试过了,它对我有用。

【讨论】:

  • 这不是同一个问题。是的,也有一些转换,但是这个问题的四舍五入使您的链接讨论不足以获得完整的答案。
【解决方案2】:

使用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'])

【讨论】:

  • 太干净了,这应该是imo的答案。
【解决方案3】:

使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 2014-11-23
    • 2020-11-22
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多