{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Datetime Functionality\n",
"The datetime module is fully described in the Python online\n",
"documentation that you can access at\n",
"Python Docs: datetime . We'll begin by importing\n",
"the three different portions of the module that we are going to use\n",
"at various points throughout the book, `datetime`, `timedelta`, and `time`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from datetime import datetime, timedelta, time"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## datetime objects\n",
"\n",
"Now let's learn about and use the datetime objects\n",
"from the datetime module. In meteorology we can't concern\n",
"ourselves with every local time zone, especially when various locations\n",
"have daylight savings times and other locations don't. As a result,\n",
"meteorologists use a common time coordinate called Universal time (UTC\n",
"or Zulu). This time never changes, there is no daylight savings time and\n",
"it is the same at every location around the globe. To get the time in\n",
"UTC"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(datetime.utcnow())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following should be similar to the output that you see on your\n",
"screen:\n",
"\n",
"`2020-01-01 21:53:38.422386`\n",
"\n",
"This is the default print format of the datetime object,\n",
"\n",
"`YYYY-MM-DD HH:MM:SS.ms`\n",
"\n",
"Now let's save it to a variable name to be more useful:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"now = datetime.utcnow()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The new variable we created (called `now`) is really so much more than\n",
"simply holding the time; it is an object that contains various methods\n",
"for access information from our stored computer time. For example, we\n",
"may not want to use all of the information given in the default output\n",
"from the date command, like we had above. Using the various methods\n",
"and/or formatting statements will allow us to specify what information\n",
"we want (e.g., year, month, day) and get its numeric or character value.\n",
"Here are a couple of common methods for getting numeric elements out of\n",
"our datetime object:\n",
"\n",
"`now.day`\n",
"\n",
"`now.hour`\n",
"\n",
"`now.minute`\n",
"\n",
"`now.second`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(now)\n",
"print(now.year)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To get a particular date format using the following list of format types\n",
"(all begin with a percent sign;\n",
"Python Docs: strftime-and-strptime-format-codes).\n",
"Here we are going to do an example using the f-string (formatted\n",
"string):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(f'The current year is {now:%Y}')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can combine the format statements to form strings, for example,\n",
"write a Python print statement to get the year, month, and day in one\n",
"continuous string (`YYYYMMDD`):\n",
"\n",
"What is the result of the date function you wrote?
\n",
"\n",
"How about printing out the Month in a word abbreviation form?
\n",
"\n",
"Any of the Python statements given above can be assigned to a variable\n",
"name to be used anywhere within your program. We'll continue to come\n",
"back to aspects of the datetime objects throughout the semester."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Set your own time\n",
"We are not beholden to only using the current date/time -- we can set any date/time we want. For example, let's set a date of May 23, 2018 at 12 UTC, we can use the `datetime` module again by setting the the year, month, day, hour, minute, second. \n",
"\n",
"```{note}\n",
"When setting your own time, the year, month, and day are required (in that exact order) and it no hour, minute, or second then they will be assumed to be zero.\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Set your own time\n",
"date = datetime(2018, 5, 23, 12)\n",
"print(date)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## timedelta objects\n",
"\n",
"There will be moments where you'll want to do some math with the date (e.g., what time is 6 hours from now?)\n",
"and timedelta objects makes that arithmatic\n",
"very easy. Using the `timedelta` functionality we can add or substract\n",
"days, seconds, microseconds, milliseconds, minutes, hours, or weeks.\n",
"\n",
"Let's try this out by finding what was the datetime 12 hours ago (subtraction) and what will it be two weeks from now (addition):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 12 hours ago\n",
"print(now - timedelta(hours=12))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So above, we used our previously defined current time, `now`, and substracted using `timedelta` twelve hours. It was seamless for the combination of the `datetime` and `timedelta` objects to know that it had to role back one date in addition to subtracting the correct number of hours."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"future_time = now + timedelta(weeks=2)\n",
"print(future_time)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we saved our time calculation to a new variable, `future_time`, and printed it out. Again, we let the computer do the hard work for us."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## time objects\n",
"\n",
"The time objects deal with only the local\n",
"time (hours, minutes, seconds, etc.) and are a subset of the `datetime` objects. We can use this to help\n",
"us set a datetime object more efficiently when we may want to get a relatively current date, but set the\n",
"hour to a specific time.\n",
"\n",
"Let's find the date of yesterday and set the time to 12 UTC."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Use datetime and timedelta to get the date of yesterday\n",
"yesterday = datetime.utcnow() - timedelta(days=1)\n",
"print(yesterday)\n",
"\n",
"# Use time to set a 12 UTC time\n",
"hour = time(12)\n",
"print(hour)\n",
"\n",
"# Use the combine method to set a new datetime object\n",
"new_date = datetime.combine(yesterday, hour)\n",
"print(new_date)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "metpy_book",
"language": "python",
"name": "python3"
},
"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.5"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}