Datetime Module =============== .. toctree:: :maxdepth: 1 Indices and tables ------------------ * :ref:`genindex` * :ref:`modindex` * :ref:`search` .. _section_heading-Datetime_Introduction: Introduction ------------ Applications commonly have to interpret, manipulate and print date and time values. The :py:mod:`datetime` module provides a rich set of standardized functionality to make it easy for you to integrate platform independent code into your application. The :py:mod:`datetime` module provides several objects and they generally fall into one of 2 categories: * Aware - Has knowledge of time adjustments like time zones and daylight savings time. Due to awareness, these object types can properly represent a specific moment in time relative to other objects that are also aware. * Naive - Lacks "awareness" properties (mind...blown). Therefore, it is not always possible to identify exactly what the moment of time is compared to other naive or aware objects. For example, stating it's 8pm without giving the timezone, does not actually tell you the time with-respect-to a known datum (UTC), and therefore without a known reference point, this 'time' can't be compared to other 'times'. Naive objects are generally easier to work with since, in a lot of situations, you can ignore obtaining the information necessary to make an object "aware". For example, saying a data sample was acquired 28 seconds after starting the program, does not require an aware object to make the time value meaningful. There are many classes defined in the :py:mod:`datetime` that you should familiarize yourself with. However, only 2 will be discussed in detail here. .. _section_heading-timedelta_Class: timedelta Class --------------- **MUTABILITY:** Immutable A type that represents the difference between two dates or times. .. py:function:: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) All arguments are optional, may be of class :py:class:`int` or :py:class:`float`, can be positive or negative, and default to 0. Internally, the :py:class:`~datetime.timedelta` class converts the time-delta into units of days, seconds and microseconds only (fractional microseconds, if they exist, are rounded off). As a result, only these characteristic attributes of the time delta can be obtained from the :py:class:`~datetime.timedelta` object. Instances of :py:class:`~datetime.timedelta` are considered :py:data:`True` if they don't equal ``timedelta(0)``. We can explore some (but not all) of the attributes available to the :py:class:`~datetime.timedelta` objects. First, lets create some :py:class:`~datetime.timedelta` objects to work with: >>> from datetime import timedelta >>> t0 = timedelta(1, 2, 3, 4, 5, 6, 7) >>> t0 datetime.timedelta(50, 21902, 4003) >>> t1 = timedelta(21, 22, 23, 24, 25, 26, 27) >>> t1 datetime.timedelta(211, 8722, 24023) * Printing time-delta information >>> str(t0) '50 days, 6:05:02.004003' >>> print(t0) 50 days, 6:05:02.004003 >>> repr(t0) 'datetime.timedelta(50, 21902, 4003)' * Obtaining time-delta information >>> t0.days 50 >>> t0.seconds 21902 >>> t0.microseconds 4003 >>> t0.total_seconds() 4341902.004003 Instances of :py:class:`~datetime.timedelta` objects support many of the typical math operators that work on :py:class:`int` and :py:class:`float` objects. For example: * Adding and subtracting >>> t0 + t1 datetime.timedelta(261, 30624, 28026) >>> t0 - t1 datetime.timedelta(-161, 13179, 979980) * Multiplication and division >>> t0 * 5 datetime.timedelta(251, 23110, 20015) >>> t0 / t1 0.23805433168790804 >>> t0 / 5 datetime.timedelta(10, 4380, 400801) >>> t0 // t1 0 >>> t0 // 5 datetime.timedelta(10, 4380, 400800) >>> t0 % 5 datetime.timedelta(50, 21902, 4003) >>> quotient, remainder = divmod(t0, t1) >>> quotient 0 >>> remainder datetime.timedelta(50, 21902, 4003) * Unary operations >>> id(t0) 140628001935808 >>> id(+t0) # '+' returns a copy of t0 timedelta object 140628001938568 >>> -t0 datetime.timedelta(-51, 64497, 995997) >>> abs(t0) datetime.timedelta(50, 21902, 4003) .. _section_heading-datatime_Class: datetime Class -------------- **MUTABILITY:** Immutable This is a class within the :py:mod:`datetime` module, not the module itself. A :py:class:`~datetime.datetime` object combines a :py:class:`~datetime.date` and a :py:class:`~datetime.time` object together to represent a specific moment in time. .. py:function:: datetime(year, month, day, hour=0, minute=0, second=0, tzinfo=None) If the ``tzinfo`` argument is provided, the object is aware. Otherwise, it is naive. Except for ``tzinfo``, all arguments are :py:class:`int`. We can explore some (but not all) of the attributes available to the :py:class:`~datetime.datetime` objects. First, lets create some :py:class:`~datetime.datetime` objects to work with: >>> from datetime import datetime >>> from datetime import timedelta >>> from datetime import timezone >>> import time >>> # >>> # Create a timezone object to represent UTC-5 >>> # >>> my_timezone = timezone(timedelta(hours=-5)) >>> # >>> # Create some aware datetime objects >>> # >>> dt0 = datetime(2018, 3, 12, 9, 37, 34, 100, my_timezone) >>> dt1 = datetime.now(my_timezone) .. tip:: Consider the ``pytz`` package for a slicker method for specifying timezones. * Printing :py:class:`~datetime.datetime` objects returns `iso8601 `_ formatted strings: >>> print(dt0) 2018-03-12 09:37:34.000100-05:00 >>> print(dt1) 2018-03-12 20:59:37.447286-05:00 .. tip:: There is an international standard for representing date and time values called `iso8601 `_. Due to it being more natural to interpret :py:class:`~datetime.datetime` values when printed (and not viewing their repr output), the output from the examples will be wrapped in :py:func:`print` statements. * Obtaining the current time >>> print(datetime.now(my_timezone)) 2018-03-12 21:08:18.077444-05:00 * Obtaining a :py:class:`~datetime.datetime` object from a POSIX timestamp (such as from :py:func:`~time.time`) >>> print(datetime.fromtimestamp(time.time(), my_timezone)) 2018-03-12 21:07:02.917972-05:00 * Convert a datetime object into a POSIX timestamp: >>> print(dt0) 2018-03-12 09:37:34.000100-05:00 >>> dt0.timestamp() 1520865454.0001 * Obtain a :py:class:`~datetime.datetime` object by parsing a string according to a given format: >>> print(datetime.strptime('Tue Jun 17, 2008', '%a %b %d, %Y')) 2008-06-17 00:00:00 * Output a :py:class:`~datetime.datetime` object using a specific format string: >>> print(dt0) 2018-03-12 09:37:34.000100-05:00 >>> dt0.strftime('%a %b %d, %Y') 'Mon Mar 12, 2018' * Obtaining attributes about a :py:class:`~datetime.datetime` value: >>> print(dt0) 2018-03-12 09:37:34.000100-05:00 >>> dt0.year 2018 >>> dt0.month 3 >>> dt0.day 12 >>> dt0.hour 9 >>> dt0.minute 37 >>> dt0.second 34 >>> print(dt0.tzinfo) UTC-05:00 >>> print(dt0.date()) 2018-03-12 >>> print(dt0.time()) 09:37:34.000100 >>> dt0.weekday() # Monday=0, Sunday=6 0 >>> dt0.isoweekday() # Monday=1, Sunday=7 1 >>> dt0.isocalendar() # ISO Year, ISO week num, ISO weekday (2018, 11, 1) >>> dt0.isoformat() # ISO 8601 format output '2018-03-12T09:37:34.000100-05:00' * Alter attributes of the :py:class:`~datetime.datetime` value: >>> print(dt0) 2018-03-12 09:37:34.000100-05:00 >>> dt2 = dt0.replace(year=2099) >>> print(dt2) 2099-03-12 09:37:34.000100-05:00 Any of the attributes (year, month, day, hour, minute, second, microsecond and tzinfo, given as keyword argument) can be replaced in the :py:class:`~datetime.datetime` object using this method. * :py:class:`~datetime.datetime` objects can be added and subtracted with timedelta >>> print(dt0) 2018-03-12 09:37:34.000100-05:00 >>> print(dt0 + timedelta(hours=5)) 2018-03-12 14:37:34.000100-05:00 >>> print(dt0 - timedelta(hours=5)) 2018-03-12 04:37:34.000100-05:00 * Subtracting two :py:class:`~datetime.datetime` objects yields the :py:class:`~datetime.timedelta` between them: >>> print(dt0) 2018-03-12 09:37:34.000100-05:00 >>> print(dt1) 2018-03-12 20:59:37.447286-05:00 >>> print(dt1 - dt0) 11:22:03.447186 * You can compare :py:class:`~datetime.datetime` objects just like other numerical objects: >>> print(dt0) 2018-03-12 09:37:34.000100-05:00 >>> print(dt1) 2018-03-12 20:59:37.447286-05:00 >>> dt0 < dt1 True >>> dt0 == dt1 False >>> dt0 > dt1 False .. _iso8601Wikipedia: https://en.wikipedia.org/wiki/ISO_8601