Using timezones in your Python scripts

pytz allows accurate and cross platform timezone calculations using Python. Here is a small example on how to display date and time for differents timezones using a Zope Utility.

pytz - World Timezone Definitions for Python

1. Create an utility which provides a getCurrentTimes fonction (file utils.py)

# Python imports
from datetime import datetime
import pytz

# Zope imports
from zope.interface import Interface, implements
from zope.component import provideUtility

class ITimezoneUtils(Interface):
    """ Utilities for timezone calculations """

    def getCurrentTimes(timezones, fmt=None):
        """ Return current time for a list of timezones.

        >>> getCurrentTimes(['Europe/London', 'Asia/Tokyo'])
        {'Europe/London': datetime.datetime(2009, 7, 9, 20, 29, 26, 603590, 
                          tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>),
        'Asia/Tokyo': datetime.datetime(2009, 7, 10, 4, 29, 26, 603590, 
                          tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>)}

        >>> getCurrentTimes(['Europe/London', 'Asia/Tokyo'], fmt='%Y-%m-%d %H:%M')
        {'Europe/London': '2009-07-09 20:31',
         'Asia/Tokyo': '2009-07-10 04:31'}
        """

class TimezoneUtils(object):

    implements(ITimezoneUtils)

    def getCurrentTimes(self, timezones, fmt=None):

        # Get UTC current time
        now_utc = datetime.now(pytz.timezone('UTC')) 

        # Compute current time for each timezone
        result = {}

        for tz in timezones:
            now_tz = now_utc.astimezone(pytz.timezone(tz))

            if fmt is not None:
                now_tz = now_tz.strftime(fmt)

            result[tz] = now_tz

        return result

provideUtility(TimezoneUtils(), ITimezoneUtils)

2. Use this utility to compute date and time for multiple timezones

>>> # Zope imports
>>> from zope.component import getUtility

>>> from utils import ITimezoneUtils
>>> tz_utils = getUtility(ITimezoneUtils)
>>> timezones = ['Europe/London', 'Asia/Tokyo', 'America/New_York']

>>> tz_utils.getCurrentTimes(timezones)
{'America/New_York': datetime.datetime(2009, 7, 9, 15, 32, 18, 910813, 
                          tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>), 
 'Europe/London': datetime.datetime(2009, 7, 9, 20, 32, 18, 910813, 
                          tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>), 
 'Asia/Tokyo': datetime.datetime(2009, 7, 10, 4, 32, 18, 910813, 
                          tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>)}

>>> tz_utils.getCurrentTimes(timezones, fmt='%Y-%m-%d %H:%M')
{'America/New_York': '2009-07-09 15:32', 
 'Europe/London': '2009-07-09 20:32', 
 'Asia/Tokyo': '2009-07-10 04:32'}
Add comment

Vous pouvez ajouter un commentaire en complétant le formulaire ci-dessous. Le format doit être plain text. Les commentaires sont modérés.

Question: What is 10 + four ?
Votre réponse: