本文介绍了将tzinfo插入到datetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"

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

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

是有一些方法可以以下列方式将 tzinfo 插入到 datetime 对象中?

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)


推荐答案

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

这篇关于将tzinfo插入到datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 10:30