Skip to content

Instantly share code, notes, and snippets.

@bryanchow
Created September 5, 2011 20:34
Show Gist options
  • Save bryanchow/1195854 to your computer and use it in GitHub Desktop.
Save bryanchow/1195854 to your computer and use it in GitHub Desktop.

Revisions

  1. bryanchow revised this gist Sep 5, 2011. 1 changed file with 8 additions and 4 deletions.
    12 changes: 8 additions & 4 deletions utcisoformat.py
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,9 @@
    # Convert Django DateTimeField values to ISO format in UTC
    # Useful for making Django DateTimeField values compatible with the
    # jquery.localtime plugin.
    #
    # https://gist.github.com/1195854

    from pytz import timezone, utc
    from django.conf import settings

    @@ -11,9 +17,7 @@
    def utcisoformat(dt):
    """
    Return a datetime object in ISO 8601 format in UTC, without microseconds
    or time zone offset other than 'Z', e.g. '2011-06-28T00:00:00Z'. Useful
    for making Django DateTimeField values compatible with the
    jquery.localtime plugin.
    or time zone offset other than 'Z', e.g. '2011-06-28T00:00:00Z'.
    """
    # Convert datetime to UTC, remove microseconds, remove timezone, convert to string
    return TZ.localize(dt.replace(microsecond=0)).astimezone(utc).replace(tzinfo=None).isoformat() + 'Z'
    return TZ.localize(dt.replace(microsecond=0)).astimezone(utc).replace(tzinfo=None).isoformat() + 'Z'
  2. bryanchow created this gist Sep 5, 2011.
    19 changes: 19 additions & 0 deletions utcisoformat.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    from pytz import timezone, utc
    from django.conf import settings


    # A pytz.timezone object representing the Django project time zone
    # Use TZ.localize(mydate) instead of tzinfo=TZ to ensure that DST rules
    # are respected
    TZ = timezone(settings.TIME_ZONE)


    def utcisoformat(dt):
    """
    Return a datetime object in ISO 8601 format in UTC, without microseconds
    or time zone offset other than 'Z', e.g. '2011-06-28T00:00:00Z'. Useful
    for making Django DateTimeField values compatible with the
    jquery.localtime plugin.
    """
    # Convert datetime to UTC, remove microseconds, remove timezone, convert to string
    return TZ.localize(dt.replace(microsecond=0)).astimezone(utc).replace(tzinfo=None).isoformat() + 'Z'