14

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)
Kit
  • 30,365
  • 39
  • 105
  • 149

1 Answers1

19
def transform_date(date_string, tzinfo):
    fmt = '%Y-%m-%d'
    date = datetime.strptime(date_string, fmt).replace(tzinfo=tzinfo)
    return date
agf
  • 171,228
  • 44
  • 289
  • 238
  • 1
    fwiw, not to be used with pytz objects: https://stackoverflow.com/a/25390097/, https://stackoverflow.com/a/26266741/ – arturomp Mar 10 '20 at 07:15