1

Given the example below:

import datetime
import pprint
import time

now_unaware = datetime.datetime.now()
print "Time gotten from the OS: " 
pprint.pprint now_unaware                   
     #OUTPUT: datetime.datetime(2016, 4, 7, 17, 4, 54, 689054)
     #COMMENT: The time is correct for the zone, but now_unaware doesn't explicitly know what zone is this. 
print "My timezone:"
pprint.pprint(time.tzname[time.daylight])   
     ##OUTPUT: 'CEST'

Please confirm or disprove my assumptions.

Assumptions

Given the above information above I should have enough information to:

  • Make now_unaware aware of the timezone without any timezone hard coding because 'CEST' unambiguously defines a relation to UTC
  • Be able to convert now_unaware to UTC without importing any additional libraries
  • Not being able to do this given the above information is either a python design flaw or a wrong mindset on approaching the problem
TheMeaningfulEngineer
  • 13,149
  • 20
  • 73
  • 132

1 Answers1

1

Your first assumption is correct. It sounds like you want to localize your unaware time object.

Your second assumption is somewhat correct. In Python 3 it's easier to work with timezones with only the standard library thanks to datetime.timezone.

But in Python 2, it cannot be done easily with only the standard library. You will need to subclass tzinfo. Look at the "Example tzinfo classes" in the tzinfo link.

Finally, you've got the right mindset about approaching the problem. It would indeed be nice to do this only using the standard library. I think Python 3 addresses that, and that's why Python 2 users tend to add the pytz package to their projects.

If you're interested, there is a lengthy discussion about it here.

nofinator
  • 2,559
  • 17
  • 21