{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Datetime notebook, ATM350 Spring 2024 " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Imports" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "import datetime\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The `datetime` module includes the following *classes*:\n", "1. **date**\n", "1. **datetime**\n", "1. **time**\n", "1. **timedelta**\n", "1. **timezone**\n", "1. **tzinfo**\n", "\n", "datetime, timedelta, date, time, tzinfo, timezone" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### It also includes these associated **methods**:\n", "1. **strftime**\n", "1. **strptime**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Get the current time by making a call to datetime's datetime.now method. It produces a datetime object with the year, month, day, hour, minute, second and microsecond." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "x = datetime.datetime.now()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "x" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### This datetime object contains a variety of **attributes** that we can list, as well as reformat." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "x.year" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "x.month" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### We can use the strftime method on a datetime object in order to produce date/time strings in a specified format. \n", "#### We'll play around with a few of these options in the cells below, but visit https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior for full documentation of strftime!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "# %A or %a will list the full name of the day of the week:\n", "x.strftime(\"%A\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "# %y will list the two-digit year, %m, the two-digit month, and %d, the two-digit date:\n", "print(x.strftime(\"%y\"))\n", "print(x.strftime(\"%m\"))\n", "print(x.strftime(\"%d\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Let's combine the year, month, and day, into a date string we're used to using in ATM 350! We can define a new object called today as the output from our strftime method, still using our the datetime object \"x\" we created using the datetime.now() method:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "today = x.strftime(\"%y is the year, %m is the month, and %d is the day\")\n", "print(today)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "# Let's add the hour to that!\n", "x.strftime(\"%y%m%d%H\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "# What if we wanted to define a more human-friendly string to use in a title of a graphic?\n", "x.strftime(\"%y%m%d at %HZ\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise: Using the documentation in the link below, create a title string from today's date in the format: \"DD Month YYYY at HHMM UTC\". For example: 10 June 1983 at 1435 UTC :\n", "https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Enter your code here:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "# %load /spare11/atm350/common/feb29/datetime_1.py\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### We can also create datetime objects with the datetime.datetime() class constructor." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "y = datetime.datetime(2024,5,14,17,29,0)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "y" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "print(y.year)\n", "print(y.month)\n", "print(y.hour)\n", "print(y.minute)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Besides the datetime class, there is also just a plain date class, that only deals with dates (not times). A \"time\" class also exists with a similar purpose." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "from datetime import date, time" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "a = date(2024,11,2)\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Just as there was a *now()* method for the `datetime` class, there is a *today()* method for the `date` class." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "today = date.today()\n", "print(\"Current date = \", today)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "print (\"Current year is: \", today.year)\n", "print (\"Current month is: \", today.month)\n", "print (\"Current day is: \", today.day)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Here are some examples of the `time` class of datetime objects:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "# time(hour = 0, minute = 0, second = 0) ... In other words, no arguments provided, so defaults of 0 are used for hour, minute, and second:\n", "a = time()\n", "print(\"a =\", a)\n", "\n", "# time(hour, minute and second)\n", "b = time(7, 29, 18)\n", "print(\"b =\", b)\n", "\n", "# time(hour, minute and second)\n", "c = time(hour = 7, minute = 29, second = 18)\n", "print(\"c =\", c)\n", "\n", "# time(hour, minute, second, microsecond)\n", "d = time(7, 29, 18, 679122)\n", "print(\"d =\", d)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### These look like strings. Are they?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "type(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### No ... they are datetime objects of class time." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### We can also call specific attributes of these objects:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "print(\"hour =\", d.hour)\n", "print(\"minute =\", d.minute)\n", "print(\"second =\", d.second)\n", "print(\"microsecond =\", d.microsecond)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### It is \"cleaner\" to import the various classes available to us in the datetime library by importing them in the following way (we will discuss timedelta shortly!). Note that this allows us to just call the class \"datetime\" as opposed to datetime.datetime.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "from datetime import datetime, timedelta" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "#A few examples of creating datetime objects:\n", "\n", "#datetime(year, month, day)\n", "a = datetime(2024, 11, 28)\n", "print(a)\n", "\n", "# datetime(year, month, day, hour, minute, second, microsecond)\n", "b = datetime(2006, 4, 23, 23, 55, 59, 342380)\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### We can also use some basic arithmetic to calculate time between dates!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "t1 = date(year = 2024, month = 7, day = 12)\n", "t2 = date(year = 2023, month = 12, day = 23)\n", "t3 = t1 - t2\n", "print(\"t3 =\", t3)\n", "\n", "t4 = datetime(year = 2018, month = 7, day = 12, hour = 7, minute = 9, second = 33)\n", "t5 = datetime(year = 2019, month = 6, day = 10, hour = 5, minute = 55, second = 13)\n", "t6 = t4 - t5\n", "print(\"t6 =\", t6)\n", "\n", "print(\"type of t3 =\", type(t3)) \n", "print(\"type of t6 =\", type(t6)) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Datetime's timedelta class allows us to easily compute dates and times earlier or later than a base time.\n", "### Note that these objects are defined as a period of time, rather than a date." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "t1 = timedelta(weeks = 2, days = 5, hours = 1, seconds = 33)\n", "t2 = timedelta(days = 4, hours = 11, minutes = 4, seconds = 54)\n", "t3 = t1 + t2\n", "\n", "print(\"t3 =\", t3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "t1 = timedelta(seconds = 33)\n", "t2 = timedelta(seconds = 54)\n", "t3 = t1 - t2\n", "\n", "print(\"t3 =\", t3)\n", "print(\"t3 =\", abs(t3))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Timedelta includes a total_seconds() method:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "t = timedelta(days = 6, hours = 13, seconds = 53, microseconds = 232436)\n", "print(\"total seconds =\", t.total_seconds())\n", "print(\"total minutes =\", t.total_seconds()/60)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Note that \"months\" is not a valid timedelta argument!! Why not?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "t1 = timedelta (months = 1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### However, if our `datetime` object includes a month, we *can* compute a time delta in months via the `relativedelta` function from a separate package, `dateutil`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "from dateutil.relativedelta import relativedelta\n", "\n", "today + relativedelta(months=2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### As we learned at the beginning of this notebook, datetime's datetime class includes the strftime method which takes a datetime object and converts it into a string, which can be formatted. Review from earlier..." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# current date and time\n", "curtime = datetime.now()\n", "\n", "string1 = curtime.strftime(\"%H:%M:%S\")\n", "print(\"string1:\", string1)\n", "\n", "string2 = curtime.strftime(\"%m/%d/%Y, %H:%M:%S\")\n", "# mm/dd/YY H:M:S format\n", "print(\"string2:\", string2)\n", "\n", "string3 = curtime.strftime(\"%d/%m/%Y, %H:%M:%S\")\n", "# dd/mm/YY H:M:S format\n", "print(\"string3:\", string3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Conversely, the strptime method takes an appropriately-formatted date/time string and converts it into a datetime object." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Start with a string:\n", "date_string = \"10 June, 2023\"\n", "print(\"date_string =\", date_string)\n", "\n", "#Convert to a date object, making sure to include the appropriate formatting we used in the string:\n", "date_object = datetime.strptime(date_string, \"%d %B, %Y\")\n", "print(\"date_object =\", date_object)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Calculate a new date and convert it into its string representation" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "new_date_object = date_object + timedelta (days=14)\n", "print(new_date_object)\n", "new_date_string = new_date_object.strftime (\"%d %B, %Y\")\n", "print(new_date_string)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise: Create a date object from a string \"1900 UTC 22 May 2014\" " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Enter your code here:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "# %load /spare11/atm350/common/feb29/datetime_2.py\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Timezone can be manipulated via the pytz library. pytz stands for Python Time Zone." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pytz\n", "\n", "# What time is our computer set to?\n", "system = datetime.now()\n", "print(\"system:\", system.strftime(\"%m/%d/%Y, %H:%M:%S\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Here we can pass a specific time zone into the datetime.now() method:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tz_NY = pytz.timezone('America/New_York') \n", "datetime_NY = datetime.now(tz_NY)\n", "print(\"NY:\", datetime_NY.strftime(\"%m/%d/%Y, %H:%M:%S\"))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tz_Amsterdam = pytz.timezone('Europe/Amsterdam')\n", "datetime_Amsterdam = datetime.now(tz_Amsterdam)\n", "print(\"Amsterdam:\", datetime_Amsterdam.strftime(\"%m/%d/%Y, %H:%M:%S\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## References\n", "\n", "1. https://docs.python.org/3/library/datetime.html \n", "1. https://foundations.projectpythia.org/core/datetime/datetime.html\n", "1. https://www.w3schools.com/python/python_datetime.asp\n", "1. https://www.programiz.com/python-programming/datetime\n", "1. https://dateutil.readthedocs.io/en/stable/index.html" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 Jan. 2024 Environment", "language": "python", "name": "jan24" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.7" } }, "nbformat": 4, "nbformat_minor": 4 }