如何将钟摆转换为datetime.datetime类型?

时间:2019-01-03 19:04:08

标签: python datetime pendulum

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

这对于datetime.datetime类型可以很好地工作,我仍然必须使用摆锤v1.4。

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

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

4 个答案:

答案 0 :(得分:1)

我也找不到为此的摆锤助手。因此,回到基础:

using System;
using System.Diagnostics;

var proc = new ProcessStartInfo()
{
  UseShellExecute = true,
  Verb = "runas",
  WindowStyle = ProcessWindowStyle.Hidden,
  FileName = "powershell.exe",
  Arguments = "-NoProfile -Command " + command
};
Process.Start(proc).WaitForExit();

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

答案 1 :(得分:1)

对此有另一种看法:

>>> from datetime import datetime
>>> import pendulum
>>> datetime.fromtimestamp(pendulum.now().timestamp())
datetime.datetime(2019, 3, 20, 16, 32, 24, 172283)

但是,实际上,没有必要:pendulum的{​​{1}}继承自DateTime,因此任何与stdlib的datetime.datetime一起工作的代码也应该工作。

答案 2 :(得分:1)

Pendulum 对象具有受保护的 _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]>)

答案 3 :(得分:-4)

使用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')]
相关问题