【问题标题】:Insert a tzinfo into datetime将 tzinfo 插入日期时间
【发布时间】:2011-10-12 16:48:51
【问题描述】:

我有以下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)

【问题讨论】:

    标签: python datetime timezone tzinfo


    【解决方案1】:
    def transform_date(date_string, tzinfo):
        fmt = '%Y-%m-%d'
        date = datetime.strptime(date_string, fmt).replace(tzinfo=tzinfo)
        return date
    

    【讨论】:

    猜你喜欢
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 2021-03-22
    • 2016-02-02
    相关资源
    最近更新 更多