Question
I want to convert the current time to +0900 in Python. What's the appropriate way to do this (assuming in the time module)?
How-To
You can use the datetime module instead. Adapted from:
https://docs.python.org/3/library/datetime.html#datetime.tzinfo.fromutc
- test.py
- #!/usr/bin/env python
- from datetime import tzinfo, timedelta, datetime
- class FixedOffset(tzinfo):
- def __init__(self, offset):
- self.__offset = timedelta(hours=offset)
- self.__dst = timedelta(hours=offset-1)
- self.__name = ''
- def utcoffset(self, dt):
- return self.__offset
- def tzname(self, dt):
- return self.__name
- def dst(self, dt):
- return self.__dst
- fmt = "%Y-%m-%d %H:%M:%S %Z%z"
- print datetime.now().strftime(fmt)
- print datetime.now(FixedOffset(9)).strftime(fmt)
Supplement
* Converting time zones for datetime objects in Python
沒有留言:
張貼留言