Python - datetime

From PeformIQ Upgrade
Revision as of 21:49, 18 October 2010 by PeterHarding (talk | contribs)
Jump to navigation Jump to search

References

Examples

Simple Example

#!/usr/bin/env python

import datetime

start_date = datetime.datetime(2007,01,01)
end_date   = datetime.datetime(2008,03,11)

print start_date
print end_date

date = start_date

print 'Date'

while date < end_date:
   print date.strftime('%Y-%m-%d')

   date += datetime.timedelta(days=1)

Examples of Range of Functions

#!/usr/bin/env python
#
#  $Id:$
#
#---------------------------------------------------------------------

import sys
import getopt

from datetime import datetime, timedelta

#---------------------------------------------------------------------
"""
From datetime documentation...

def astimezone(self, tz):
   if self.tzinfo is tz:
      return self
   # Convert self to UTC, and attach the new time zone object.
   utc = (self - self.utcoffset()).replace(tzinfo=tz)
   # Convert from UTC to tz's local time.
   return tz.fromutc(utc)
"""

#---------------------------------------------------------------------

def display(dt):
   print "  timetuple() -> %s" % dt.timetuple()
   print "   strftime() -> %s" % dt.strftime("%Y-%m-%d %H:%M:%S")
   print "isocalendar() -> %s" % str(dt.isocalendar())
   print "    weekday() -> %d" % dt.weekday()
   print " isoweekday() -> %d" % dt.isoweekday()
   print "  isoformat() -> %s" % dt.isoformat()
   print "    __str__() -> %s" % dt.__str__()
   print "      ctime() -> %s" % dt.ctime()
   print "     tzname() -> %s" % dt.tzname()
   print "        dst() -> %s" % dt.dst()
   print "     timetz() -> %s" % dt.timetz()

#---------------------------------------------------------------------

def test():
   now = datetime.now()

   print "now():"
   display(now)

   utcnow = datetime.utcnow()

   print "utcnow():"
   display(utcnow)

   plus_1_day = now + timedelta(days=1)

   print "plus_1_day():"
   display(plus_1_day)

   plus_2_day = now + timedelta(days=2)

   print "plus_2_day():"
   display(plus_2_day)

#---------------------------------------------------------------------

def usage():
   USAGE = """
   
     Usage:
     
       $ dt.py
    
   """
   
   sys.stderr.write(USAGE)
   
#---------------------------------------------------------------------

def main(argv):
   global logfile, verbose_flg

   #----- Process command line arguments ----------------------------

   try:
      opts, args = getopt.getopt(argv, "hl:u:t", ["help", "logfile=", "verbose"])
   except getopt.GetoptError:
      usage()
      sys.exit(2)
   else:
      for opt, arg in opts:
         if opt in ("-h", "--help"):
            usage()
            sys.exit(0)
         elif opt in ("-l", "--logfile"):
            logfile = arg
         elif opt in ("-v", "--verbose"):
            verbose_flg = True

   test()

#---------------------------------------------------------------------

if __name__ == "__main__":
   main(sys.argv[1:])

#---------------------------------------------------------------------

Exploring datetime and time Modules

#!/usr/bin/env python

import time
import datetime
import pprint


print datetime.datetime.now()
print datetime.datetime.now().date()
print datetime.datetime.now().date().isoformat()
print datetime.datetime.now().time()

print datetime.__doc__

print
print

print "time.time() -> ", time.time()

print

pp = pprint
pp.pprint(time.__dict__)

print time.__doc__

Timezone Examples

>>> import datetime  
>>> from dateutil import tz # python dateutil offers loads of convenience: http://labix.org/python-dateutil
>>> dt = datetime.datetime(2008, 8, 21, 12, 51, 0, 0, tz.tzlocal())
>>> print repr(dt), ":", dt
datetime.datetime(2008, 8, 21, 12, 51, tzinfo=tzlocal()) : 2008-08-21 12:51:00+02:00
>>> dt_utc = dt.astimezone(tz.tzutc())
>>> print repr(dt_utc), ":", dt
datetime.datetime(2008, 8, 21, 10, 51, tzinfo=tzutc()) : 2008-08-21 12:51:00+02:00
>>> dt == dt_utc

Using strptime() and strftime()

  from datetime import datetime

  dt = datetime.strptime('10:13:15 2006-03-07', '%H:%M:%S %Y-%m-%d')

  ts = datetime.now().strftime('%Y%m%d%H%M%S')
   rdt = task.fields.ReminderDateTime

   if rdt:
      ctx.locals.ReminderDate = rdt.strftime('%Y-%m-%d')
      ctx.locals.ReminderTime = rdt.hour * 60 + rdt.minute
   else:
      ctx.locals.ReminderDate = ctx.locals.Today
      ctx.locals.ReminderTime = 630
   from time import strptime

   ...

      'ReminderDateTime'        : datetime(*strptime(ctx.locals.ReminderDateTime, '%Y-%m-%d')[0:6]) + timedelta(minutes=int(ctx.locals.ReminderTime)),

Python Documentation

Timezone

from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)
HOUR = timedelta(hours=1)

# A UTC class.

class UTC(tzinfo):
    """UTC"""

    def utcoffset(self, dt):
        return ZERO

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return ZERO

utc = UTC()

# A class building tzinfo objects for fixed-offset time zones.
# Note that FixedOffset(0, "UTC") is a different way to build a
# UTC tzinfo object.

class FixedOffset(tzinfo):
    """Fixed offset in minutes east from UTC."""

    def __init__(self, offset, name):
        self.__offset = timedelta(minutes = offset)
        self.__name = name

    def utcoffset(self, dt):
        return self.__offset

    def tzname(self, dt):
        return self.__name

    def dst(self, dt):
        return ZERO

# A class capturing the platform's idea of local time.

import time as _time

STDOFFSET = timedelta(seconds = -_time.timezone)
if _time.daylight:
    DSTOFFSET = timedelta(seconds = -_time.altzone)
else:
    DSTOFFSET = STDOFFSET

DSTDIFF = DSTOFFSET - STDOFFSET

class LocalTimezone(tzinfo):

    def utcoffset(self, dt):
        if self._isdst(dt):
            return DSTOFFSET
        else:
            return STDOFFSET

    def dst(self, dt):
        if self._isdst(dt):
            return DSTDIFF
        else:
            return ZERO

    def tzname(self, dt):
        return _time.tzname[self._isdst(dt)]

    def _isdst(self, dt):
        tt = (dt.year, dt.month, dt.day,
              dt.hour, dt.minute, dt.second,
              dt.weekday(), 0, -1)
        stamp = _time.mktime(tt)
        tt = _time.localtime(stamp)
        return tt.tm_isdst > 0

Local = LocalTimezone()


# A complete implementation of current DST rules for major US time zones.

def first_sunday_on_or_after(dt):
    days_to_go = 6 - dt.weekday()
    if days_to_go:
        dt += timedelta(days_to_go)
    return dt

# In the US, DST starts at 2am (standard time) on the first Sunday in April.
DSTSTART = datetime(1, 4, 1, 2)
# and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct.
# which is the first Sunday on or after Oct 25.
DSTEND = datetime(1, 10, 25, 1)

class USTimeZone(tzinfo):

    def __init__(self, hours, reprname, stdname, dstname):
        self.stdoffset = timedelta(hours=hours)
        self.reprname = reprname
        self.stdname = stdname
        self.dstname = dstname

    def __repr__(self):
        return self.reprname

    def tzname(self, dt):
        if self.dst(dt):
            return self.dstname
        else:
            return self.stdname

    def utcoffset(self, dt):
        return self.stdoffset + self.dst(dt)

    def dst(self, dt):
        if dt is None or dt.tzinfo is None:
            # An exception may be sensible here, in one or both cases.
            # It depends on how you want to treat them.  The default
            # fromutc() implementation (called by the default astimezone()
            # implementation) passes a datetime with dt.tzinfo is self.
            return ZERO
        assert dt.tzinfo is self

        # Find first Sunday in April & the last in October.
        start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))
        end = first_sunday_on_or_after(DSTEND.replace(year=dt.year))

        # Can't compare naive to aware objects, so strip the timezone from
        # dt first.
        if start <= dt.replace(tzinfo=None) < end:
            return HOUR
        else:
            return ZERO

Eastern  = USTimeZone(-5, "Eastern",  "EST", "EDT")
Central  = USTimeZone(-6, "Central",  "CST", "CDT")
Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
Pacific  = USTimeZone(-8, "Pacific",  "PST", "PDT")