2017年2月22日 星期三

[Python 文章收集] Converting time zones for datetime objects in Python

Source From Here
Install pytz
I am using pytz, which is a time zone definitions package. You can install it using Easy Install. On Ubuntu, do this:
# sudo easy_install --upgrade pytz

Add time zone information to a naive datetime object
>>> from datetime import datetime
>>> from pytz import timezone
>>> date_str = "2009-05-05 22:28:15"
>>> datetime_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
>>> datetime_obj
datetime.datetime(2009, 5, 5, 22, 28, 15)
>>> datetime_obj_utc = datetime_obj.replace(tzinfo=timezone('UTC'))
>>> datetime_obj_utc
datetime.datetime(2009, 5, 5, 22, 28, 15, tzinfo=)
>>> print datetime_obj_utc.strftime("%Y-%m-%d %H:%M:%S %Z%z")
2009-05-05 22:28:15 UTC+0000

Add non-UTC time zone information to a naive datetime object
datetime.replace() does not handle daylight savings time correctly. The correct way is to use timezone.localize() instead. Using datetime.replace() is OK when working with UTC as shown above because it does not have daylight savings time transitions to deal with. See the pytz documentation.
>>> from datetime import datetime
>>> from pytz import timezone
>>> date_str = "2014-05-28 22:28:15"
>>> datetime_obj_naive = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
>>> datetime_obj_naive
datetime.datetime(2014, 5, 28, 22, 28, 15)
>>> datetime_obj_pacific = datetime_obj_naive.replace(tzinfo=timezone('US/Pacific')) # Wrong way
>>> print datetime_obj_pacific.strftime("%Y-%m-%d %H:%M:%S %Z%z")
2014-05-28 22:28:15 LMT-0753
>>> datetime_obj_pacific = timezone('US/Pacific').localize(datetime_obj_naive) # Right way!
>>> print datetime_obj_pacific.strftime("%Y-%m-%d %H:%M:%S %Z%z")
2014-05-28 22:28:15 PDT-0700

Convert time zones
>>> from datetime import datetime
>>> from pytz import timezone
>>> fmt = "%Y-%m-%d %H:%M:%S %Z%z"
>>> now_utc = datetime.now(timezone('UTC')) # Current time in UTC
>>> print now_utc.strftime(fmt)
2017-02-22 16:03:10 UTC+0000
>>> now_taipei = now_utc.astimezone(timezone('Asia/Taipei')) # Convert to Asia/Taipei time zone
>>> print now_taipei.strftime(fmt)
2017-02-23 00:03:10 CST+0800
>>> now_berlin = now_pacific.astimezone(timezone('Europe/Berlin')) # Convert to Europe/Berlin time zone
>>> print now_berlin.strftime(fmt)
2017-02-22 17:03:10 CET+0100

List time zones
There are 559 time zones included in pytz. Here's how to print the Asia time zones:
  1. from pytz import all_timezones  
  2.   
  3. print len(all_timezones)  
  4. for zone in all_timezones:  
  5.     if 'Asia' in zone:  
  6.         print zone  
Execution output:
592
Asia/Aden
Asia/Almaty
Asia/Amman
Asia/Anadyr
...
Asia/Yakutsk
Asia/Yangon
Asia/Yekaterinburg
Asia/Yerevan


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...