【问题标题】:How to convert pendulum to datetime.datetime type?如何将钟摆转换为 datetime.datetime 类型?
【发布时间】:2022-02-22 21:39:07
【问题描述】:

在当前部分系统中使用了 v1.4,但使用 croniter 会导致https://github.com/sdispater/pendulum/issues/214中描述的错误

这适用于 datetime.datetime 类型,我仍然需要使用 pendulum v1.4。

所以我正在寻找如何有效地将钟摆转换为 datetime.datetime 类型的解决方案?

已经尝试将钟摆格式化为字符串并使用 dateutil.parser 进行解析。

【问题讨论】:

    标签: python datetime pendulum


    【解决方案1】:

    对此的另一种看法:

    >>> from datetime import datetime
    >>> import pendulum
    >>> datetime.fromtimestamp(pendulum.now().timestamp(), pendulum.tz.UTC)
    datetime.datetime(2021, 1, 12, 11, 41, 32, 387753, tzinfo=Timezone('UTC'))
    

    通常不需要这样做,因为pendulumDateTime 继承自datetime.datetime。任何使用 stdlib 的 datetime 的代码应该也可以使用 pendulum。

    【讨论】:

    • 不确定熊猫
    • @MisterMonk 对于 Pandas,Pendulum 纳秒必须去掉,Pandas 不支持纳秒。 pandas_friendly = pendulum_datetime.strftime("%Y-%m-%d %H:%M:%S %z") 见这里:gist.github.com/liquidgenius/195fd7ca99fb761fd0fd2c2f2c78608d 和这里:github.com/sdispater/pendulum/issues/246
    • 只是为了补充摆锤的 DateTime 在任何地方都可以工作的反例 - SQLAlchemy 不喜欢使用 pendulum 的 DateTime 并且可能会导致奇怪的问题。
    • @robertlayton 如果您尝试使用 pendulum 的 DateTime 作为列类型,例如:Column('foo', pendulum.DateTime) - 它不适合工作。
    • 感谢您的回复。我使用的是普通的 SQLAlchemy 日期时间列,但是当您将钟摆 DateTime 传递给它时,它在数据库提交时失败。我现在只是在传入之前将它包装在一个 pendulum_to_datetime 函数中。
    【解决方案2】:

    我也找不到 Pendulum 助手。所以,回到基础:

    import datetime as dt
    
    tz_info = dateutil.tz.gettz(zone_name)
    pend_time = pendulum.datetime(...)
    
    dt_time = dt.datetime(
        pend_time.year,
        pend_time.month,
        pend_time.day,
        pend_time.hour,
        pend_time.minute,
        pend_time.second,
        pend_time.microsecond,
    ).astimezone(tz_info)
    

    注意 dateutil 的使用。从 Python 3.6 开始,tzinfo 文档推荐使用 dateutil.tz 而不是 pytz 作为 IANA 时区提供程序。

    【讨论】:

      【解决方案3】:

      pendulum==1.4.0 对象具有受保护的_datetime 成员:

      import pendulum
      
      p = pendulum.now()
      p._datetime
      

      这会给你类似的东西

      datetime.datetime(2021, 5, 24, 12, 44, 11, 812937, tzinfo=<TimezoneInfo [America/New_York, EDT, -4:00:00, DST]>)
      

      另一种方法如下:适用于pendulum==1.4.0和更新的pendulum==2.1.2

      import pendulum
      from datetime import datetime
      
      p = pendulum.now()
      datetime_string = p.to_datetime_string()
      datetime.fromisoformat(datetime_string)
      
      

      这将给

      datetime.datetime(2021, 5, 24, 12, 44, 11)
      

      【讨论】:

      • 最新版 pendulum 没有_datetime成员
      • 谢谢@dindom。我编辑并扩展了答案
      【解决方案4】:

      以下代码适用于我:

      In [1]: import pendulum
      
      In [2]: import datetime
      
      In [3]: pdt = pendulum.now()
      
      In [4]: datetime.datetime.fromisoformat(pdt.to_iso8601_string())
      Out[4]: datetime.datetime(2022, 2, 22, 14, 29, 36, 812772,tzinfo=datetime.timezone(datetime.timedelta(seconds=28800)))
      

      【讨论】:

        【解决方案5】:

        使用arrow module 将钟摆转换为日期时间

        >>> arrow.get(datetime(2013, 5, 5), 'US/Pacific')
        <Arrow [2013-05-05T00:00:00-07:00]>
        

        示例:

        In [90]: import numpy as np
            ...: import pandas as pd
            ...: import pendulum
            ...: import arrow
            ...: 
            ...: def pendulum_to_datetime(x):
            ...:     return arrow.get(x, x.tz.name).datetime
        
        In [91]: dates = [pendulum.datetime(2011, 1, 2, tz='Asia/Seoul'),
            ...:             pendulum.datetime(2011, 1, 5, tz='Asia/Seoul'),
            ...:             pendulum.datetime(2011, 1, 7, tz='Asia/Seoul')]
        In [92]: dates
        Out[92]: 
        [DateTime(2011, 1, 2, 0, 0, 0, tzinfo=Timezone('Asia/Seoul')),
         DateTime(2011, 1, 5, 0, 0, 0, tzinfo=Timezone('Asia/Seoul')),
         DateTime(2011, 1, 7, 0, 0, 0, tzinfo=Timezone('Asia/Seoul'))]
        
        In [93]: dates2 = [pendulum_to_datetime(x) for x in dates]
        In [94]: dates2
        Out[94]: 
        [datetime.datetime(2011, 1, 2, 0, 0, tzinfo=tzfile('ROK')),
         datetime.datetime(2011, 1, 5, 0, 0, tzinfo=tzfile('ROK')),
         datetime.datetime(2011, 1, 7, 0, 0, tzinfo=tzfile('ROK'))]
        
        In [95]: s1 = pd.Series(np.random.randn(3), index=dates2)
        In [96]: s1
        Out[96]: 
        2011-01-02 00:00:00+09:00   -0.359771
        2011-01-05 00:00:00+09:00   -0.208608
        2011-01-07 00:00:00+09:00   -0.051233
        dtype: float64
        
        In [97]: s1.index
        Out[97]: 
        DatetimeIndex(['2011-01-02 00:00:00+09:00', '2011-01-05 00:00:00+09:00',
                       '2011-01-07 00:00:00+09:00'],
                      dtype='datetime64[ns, tzfile('ROK')]', freq=None)
        
        In [98]: s2 = pd.Series(dates2)
        In [99]: s2
        Out[99]: 
        0   2011-01-02 00:00:00+09:00
        1   2011-01-05 00:00:00+09:00
        2   2011-01-07 00:00:00+09:00
        dtype: datetime64[ns, tzfile('ROK')]
        

        【讨论】:

          猜你喜欢
          • 2022-06-15
          • 2020-05-13
          • 2016-08-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多