Times and Dates

The calendar and datetime modules provide functions and classes for date and time handling. However, they are based on an idealized Gregorian calendar, so they are not suitable for dealing with pre-Gregorian dates. Time and date handling is a very complex topic—the calendars in use have varied in different places and at different times, a day is not precisely 24 hours, a year is not exactly 365 days, and daylight saving time and time zones vary. The date-time.datetime class (but not the datetime.date class) has provisions for handling time zones, but does not do so out of the box. Third-party modules are available to make good this deficiency, for example, dateutil from www.labix. org/python-dateutil, and mxDateTime from www.egenix.com/products/python/mx-Base/mxDateTime.

The time module handles timestamps. These are simply numbers that hold the number of seconds since the epoch (1970-01-01T00:00:00 on Unix). This module can be used to get a timestamp of the machine's current time in UTC (Coordinated Universal Time), or as a local time that accounts for daylight saving time, and to create date, time, and date/time strings formatted in various ways. It can also parse strings that have dates and times.

Example: The calendar, datetime, and time Modules |

Objects of type datetime.datetime are usually created programmatically, whereas objects that hold UTC date/times are usually received from external sources, such as file timestamps. Here are some examples:

import calendar, datetime, time moon_datetime_a = datetime.datetime(1969, 7, 20, 20, 17, 40) moon_time = calendar.timegm(moon_datetime_a.utctimetuple()) moon_datetime_b = datetime.datetime.utcfromtimestamp(moon_time) moon_datetime_a.isoformat() # returns: '1969-07-20T20:17:40' moon_datetime_b.isoformat() # returns: '1969-07-20T20:17:40' time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(moon_time))

The moon_datetime_a variable is of type datetime.datetime and holds the date and time that Apollo 11 landed on the moon. The moon_time variable is of type int and holds the number of seconds since the epoch to the moon landing—this number is provided by the calendar.timegm() function which takes a time_struct object returned by the datetime.datetime.utctimetuple() function, and returns the number of seconds that the time_struct represents. (Since the moon landing occurred before the Unix epoch, the number is negative.) The moon_datetime_b variable is of type datetime.datetime and is created from the moon_time integer to show the conversion from the number of seconds since the epoch to a datetime.datetime object.* The last three lines all return identical ISO 8601-format date/time strings.

The current UTC date/time is available as a datetime.datetime object by calling datetime.datetime.utcnow(), and as the number of seconds since the epoch by calling time.time(). For the local date/time, use datetime.datetime.now() or time.mktime(time.localtime()).

0 0

Post a comment