Insert a tzinfo into datetime

浪尽此生 提交于 2019-12-10 01:52:18

问题


I have the following tzinfo concrete subclass definition:

from datetime import datetime, timedelta, tzinfo

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

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

I obtain a date string and would like to transform it into a timezone-aware datetime object. I prefer to use the following method:

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

Is there some way I could insert the tzinfo into the datetime object in the following manner?

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

回答1:


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


来源:https://stackoverflow.com/questions/6818377/insert-a-tzinfo-into-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!