【问题标题】:Can pandas.to_datetime() format unix time to local timezone?pandas.to_datetime() 可以将 unix 时间格式化为本地时区吗?
【发布时间】:2022-01-10 21:31:00
【问题描述】:

我正在尝试让 pandas.to_datetime 为我提供与我的时区相关的正确时间,但我找不到任何关于如何做到这一点的信息。

这是我制作的代码:

def _new_values_list(arg1=list()):
    import time 
    keys = arg1[1]
    sym = arg1[0]
    """
    ==========================================================================
    :param: values returned by the seperate_key_value() in the form of a
    variable. Probably something like candle_data, candleD, etc.
    ==========================================================================
    :returns: a sorted pandas DataFrame with columns for the open, high, low
    close, volume and datetime as index. It also, includes a row with the
    epoch time for easier time series calculations.
    ==========================================================================
    """

    o = []
    for vals in keys: o.append(vals['open'])

    h = []
    for vals in keys: h.append(vals['high'])

    l = []
    for vals in keys: l.append(vals['low'])

    c = []
    for vals in keys: c.append(vals['close'])

    etime = []
#     for vals in keys: etime.append((vals['datetime'])/10000)
    for vals in keys: etime.append(vals['datetime'])

    time = []
    for vals in keys:
        vals = pd.to_datetime(vals['datetime'], unit='ms')
        time.append(vals)

    vol = []
    for vals in keys: vol.append(vals['volume'])

    df = pd.DataFrame({'unix_time':etime, 'datetime': time, 'open': o, 'high': h, 'low': l, 'close': c,'volume': vol})

    return df

那么这是输出:

          unix_time            datetime    open      high       low    close  \
0     1637332200000 2021-11-19 14:30:00  342.71  343.0700  342.2000  342.810   
1     1637332260000 2021-11-19 14:31:00  342.73  343.2000  342.7100  342.710   
2     1637332320000 2021-11-19 14:32:00  342.76  342.8900  342.3101  342.875   
3     1637332380000 2021-11-19 14:33:00  342.80  342.9965  342.6800  342.810   
4     1637332440000 2021-11-19 14:34:00  342.86  343.1100  342.8600  343.080   
...             ...                 ...     ...       ...       ...      ...   
3815  1638564900000 2021-12-03 20:55:00  321.68  322.4000  321.6100  322.320   
3816  1638564960000 2021-12-03 20:56:00  322.30  322.7000  322.1600  322.450   
3817  1638565020000 2021-12-03 20:57:00  322.42  323.0800  322.1100  323.050   
3818  1638565080000 2021-12-03 20:58:00  323.05  323.0773  322.8500  322.950   
3819  1638565140000 2021-12-03 20:59:00  322.96  323.4500  322.7300  323.180   

       volume       std    volume_std  
0     1813225  0.242681  76462.813531  
1       77239  0.242681  76462.813531  
2       66437  0.242681  76462.813531  
3       42748  0.242681  76462.813531  
4       52295  0.242681  76462.813531  
  • 日期时间应该显示为 08:30:00,但不是。

  • 我可以改变吗?如果是的话怎么办?

我试着做new_data['datetime'].tz_convert('US/Central') 我收到了这个错误信息:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-93-1843a60046f9> in <module>
      3 data = _values_list(rdata)
      4 new_data = _new_values_list(rdata)
----> 5 new_data['datetime'].tz_convert('US/Central')
      6 new_data['std'] = new_data['close'] - new_data['open']
      7 new_data['std'] = new_data['std'].std()

~\anaconda3\lib\site-packages\pandas\core\generic.py in tz_convert(self, tz, axis, level, copy)
   9773             if level not in (None, 0, ax.name):
   9774                 raise ValueError(f"The level {level} is not valid")
-> 9775             ax = _tz_convert(ax, tz)
   9776 
   9777         result = self.copy(deep=copy)

~\anaconda3\lib\site-packages\pandas\core\generic.py in _tz_convert(ax, tz)
   9755                 if len(ax) > 0:
   9756                     ax_name = self._get_axis_name(axis)
-> 9757                     raise TypeError(
   9758                         f"{ax_name} is not a valid DatetimeIndex or PeriodIndex"
   9759                     )

TypeError: index is not a valid DatetimeIndex or PeriodIndex

【问题讨论】:

    标签: python pandas datetime timezone


    【解决方案1】:

    为此有一个method

    df['datetime'].dt.tz_convert('US/Central')
    

    get your time zone 使用:

    import time
    time.tzname[time.localtime().tm_isdst]
    

    您可能需要先设置要转换的原始时区:

    df['datetime'].dt.tz_localize('US/Central').dt.tz_convert('Israel')
    

    如果您的时间戳已经属于某个时区,则无需这样做:

    df = pd.DataFrame({'datetime': pd.to_datetime(['2020-1-1 19:43'], utc=True)})
    

    【讨论】:

    • 我刚刚尝试过,但没有成功,我将编辑问题以向您展示返回的内容。
    • df['datetime'].dt.tz_localize('US/Central') 是错误的,如果 df['datetime'] 是从 Unix 时间转换的天真日期时间。请注意,pandas(与原生 Python 不同)没有本地时间作为默认值。相反,默认情况下它将是 UTC,例如检查utc=Trueutc=False 的 Unix 时间转换。
    • 正确的将是例如pd.to_datetime([1637332200000], unit='ms', utc=True).dt.tz_convert(time.tzname[time.localtime().tm_isdst])
    • 是的,这就是我所拥有的 - 我只是将其分解,以便每个步骤都可以自己清楚,感谢 utc=True 的建议 :)
    猜你喜欢
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    相关资源
    最近更新 更多