0

I have a date_object.time(),it's Asia/Taipei time

date_object.time() = '10:00:00'

And I get the datetime.datetime.now with timezone Asia/Taipei

current = datetime.datetime.now(pytz.utc)
taipeitime = current.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Taipei'))

And then I combine the date_object.time() and taipeitime

combine = datetime.datetime.combine(taipeitime, date_object.time()) #Asia/Taipei time

And I have to convert the combine to UTC time But I get error:

print combine.astimezone(pytz.utc)
ValueError: astimezone() cannot be applied to a naive datetime

Please teach me how to convert this? Thank you

user2492364
  • 6,543
  • 22
  • 77
  • 147

1 Answers1

0

The .time() method for datetime looses the timezone info, use .timetz() instead eg:

>> combine = datetime.datetime.combine(taipeitime, taipeitime.timetz())
>> combine.astimezone(pytz.utc)

datetime.datetime(2014, 11, 16, 15, 13, 46, 948201, tzinfo=<UTC>)

vs

>> combine = datetime.datetime.combine(taipeitime, taipeitime.time())
>> combine.astimezone(pytz.utc)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime

see https://docs.python.org/2/library/datetime.html#datetime.datetime.timetz.

Also you can replace the timezone into the time object, e.g.

combine = datetime.datetime.combine(taipeitime,
                   taipeitime.time().replace(tzinfo=pytz.timezone('Asia/Taipei')))

will get you a timezone aware combine time. See https://docs.python.org/2/library/datetime.html#datetime.time.replace

Neil Parley
  • 86
  • 1
  • 4