python - 如何将日期时间转换为正确的格式以使用 pytz 模块

标签 python datetime datetime-format pytz

如果我在这样的列中有一堆日期时间(UTC):

63058    01/22/2018 11:00:00
63059    01/22/2018 12:00:00
63060    01/22/2018 13:00:00
Name: date, Length: 63061, dtype: object

或者这个:

DatetimeIndex(['2007-12-21 17:00:00', '2007-12-21 18:00:00',
           '2007-12-21 19:00:00', '2007-12-21 20:00:00',
           '2007-12-21 21:00:00', '2007-12-23 20:00:00',
           '2007-12-23 22:00:00', '2007-12-23 23:00:00',
           '2007-12-24 00:00:00', '2007-12-24 01:00:00',
           ...
           '2018-01-22 04:00:00', '2018-01-22 05:00:00',
           '2018-01-22 06:00:00', '2018-01-22 07:00:00',
           '2018-01-22 08:00:00', '2018-01-22 09:00:00',
           '2018-01-22 10:00:00', '2018-01-22 11:00:00',
           '2018-01-22 12:00:00', '2018-01-22 13:00:00'],
          dtype='datetime64[ns]', length=63061, freq=None)

如何将整个(列表或系列)转换为这种格式:

datetime(2016, 1, 24, 18, 0, 0, tzinfo=utc)

因为我需要使用pytz模块将UTC转换为东部时间。

当我将 astimezone().strftime() 与原始数据格式一起使用时,出现此错误:AttributeError: 'Index' object has no attribute 'astimezone'This is what I originally wanted to do ,但现在我遇到了这个问题。谢谢。

最佳答案

您可以定义一个函数来转换字符串表示形式之一,如下所示:

from datetime import datetime
import pytz

def date_from_string(s):
    "Convert ``s`` from a string to a datetime object in the UTC time zone."
    dt = datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
    return dt.replace(tzinfo=pytz.utc)

然后你可以在构造函数中将它与 map 一起使用

DatetimeIndex(map(date_from_string, [
       '2007-12-21 17:00:00', '2007-12-21 18:00:00',
       '2007-12-21 19:00:00', '2007-12-21 20:00:00',
       '2007-12-21 21:00:00', '2007-12-23 20:00:00',
       '2007-12-23 22:00:00', '2007-12-23 23:00:00',
       '2007-12-24 00:00:00', '2007-12-24 01:00:00',
       ...
       '2018-01-22 04:00:00', '2018-01-22 05:00:00',
       '2018-01-22 06:00:00', '2018-01-22 07:00:00',
       '2018-01-22 08:00:00', '2018-01-22 09:00:00',
       '2018-01-22 10:00:00', '2018-01-22 11:00:00',
       '2018-01-22 12:00:00', '2018-01-22 13:00:00']),
      dtype='datetime64[ns]', length=63061, freq=None)

文档有更多信息:

datetime.strptime(..): https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

map (..): https://docs.python.org/2/library/functions.html#map

关于python - 如何将日期时间转换为正确的格式以使用 pytz 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48449196/

相关文章:

java - 如何从 java 8 中的 LocalTime 中删除毫秒

python - 我想根据特定的单词来划分文件,并且根据这个单词我想要上面的行,然后放入newfile.txt

python - 自定义丢失问题 : inputs to eager execution function cannot be keras symbolic tensors but found

python - 如何转换为日期时间

验证时间输入的 Pythonic 方法(仅适用于 Hr、Min、Sec)

python - 如何在 Python 3.x 中使用 dateutil.relativedelta?

python - 如何在 Python 中序列化 scandir.DirEntry 以通过网络套接字发送?

Python:突破 SteamCMD 提示符

java - 如何使用 XStream 以 XML 方式格式化 java.sql.Timestamp?

python - Pandas 的日期时间默认为 1970