Python - datetime
Revision as of 10:23, 16 April 2008 by PeterHarding (talk | contribs)
Examples
#!/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)
#!/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:]) #---------------------------------------------------------------------