问题 将tzinfo插入datetime


我有以下内容 tzinfo 具体子类定义:

from datetime import datetime, timedelta, tzinfo

class ManilaTime(tzinfo):
  def utcoffset(self, dt):
    return timedelta(hours=8)

  def tzname(self, dt):
    return "Manila"

我获得了一个日期字符串,并希望将其转换为时区感知 datetime 目的。我更喜欢使用以下方法:

def transform_date(date_string, tzinfo):
  fmt = '%Y-%m-%d'
  # Where do I insert tzinfo?
  date = datetime.strptime(date_string, fmt)
  return date

有什么方法可以插入 tzinfo 进入 datetime 以下列方式对象?

manila = ManilaTime()
date = transform_date('2001-01-01', manila)

2182
2017-07-25 15:22


起源



答案:


def transform_date(date_string, tzinfo):
    fmt = '%Y-%m-%d'
    date = datetime.strptime(date_string, fmt).replace(tzinfo=tzinfo)
    return date

16
2017-07-25 15:29