{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "<small><small><i>\n", "All the IPython Notebooks in **Python Date Time Module** lecture series by Dr. Milaan Parmar are available @ **[GitHub](https://github.com/milaan9/08_Python_Date_Time_Module)**\n", "</i></small></small>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python `strftime()`\n", "\n", "In this class, you will learn to convert date, time and datetime objects to its equivalent string (with the help of examples).\n", "\n", "The **[strftime()](https://strftime.org/)** method returns a string representing date and time using **[date (@ Example 3), time (@ Example 7) or datetime (@ Example 9)](https://github.com/milaan9/08_Python_Date_Time_Module/blob/main/001_Python_datetime_Module.ipynb)** object." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example 1: datetime to string using `strftime()`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The program below converts a **`datetime`** object containing current date and time to different string formats." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2021-10-18T12:31:58.196637Z", "start_time": "2021-10-18T12:31:58.163438Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2021-10-18 18:01:58.168321\n", "year: 2021\n", "month: 10\n", "day: 18\n", "time: 18:01:58\n", "date and time: 10/18/2021, 18:01:58\n", "date and time: 18/10/2021, 18:01:58\n" ] } ], "source": [ "# Example 1: datetime to string using strftime()\n", "\n", "from datetime import datetime\n", "\n", "now = datetime.now() # current date and time\n", "print(now)\n", "\n", "year = now.strftime(\"%Y\")\n", "print(\"year:\", year)\n", "\n", "month = now.strftime(\"%m\")\n", "print(\"month:\", month)\n", "\n", "day = now.strftime(\"%d\")\n", "print(\"day:\", day)\n", "\n", "time = now.strftime(\"%H:%M:%S\")\n", "print(\"time:\", time)\n", "\n", "date_time1 = now.strftime(\"%m/%d/%Y, %H:%M:%S\")\n", "print(\"date and time:\",date_time1)\n", "\n", "date_time2 = now.strftime(\"%d/%m/%Y, %H:%M:%S\")\n", "print(\"date and time:\",date_time2)\n", "\n", "# When you run the program, the output will be something like below:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ">**Note:** Here, **`year`**, **`day`**, **`time`** and **`date_time`** are strings, whereas **`now`** is a **`datetime`** object." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## How `strftime()` works?\n", "\n", "In the above program, **`%Y`**, **`%m`**, **`%d`** etc. are format codes. The **`strftime()`** method takes one or more format codes as an argument and returns a formatted string based on it." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1. We imported **`datetime`** class from the **`datetime`** module. It's because the object of **`datetime`** class can access **`strftime()`** method.\n", "\n", "<div>\n", "<img src=\"img/idt.png\" width=\"400\"/>\n", "</div>\n", "\n", "2. The **`datetime`** object containing current date and time is stored in **`now`** variable.\n", "\n", "<div>\n", "<img src=\"img/cdt.png\" width=\"400\"/>\n", "</div>\n", "\n", "3. The **`strftime()`** method can be used to create formatted strings.\n", "\n", "<div>\n", "<img src=\"img/strff1.png\" width=\"400\"/>\n", "</div>\n", "\n", "4. The string you pass to the **`strftime()`** method may contain more than one format codes.\n", "\n", "<div>\n", "<img src=\"img/strff2.png\" width=\"400\"/>\n", "</div>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example 2: Creating string from a timestamp" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2021-10-18T12:31:58.489119Z", "start_time": "2021-10-18T12:31:58.199569Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Date time object: 2018-06-12 15:25:22\n", "Output 2: 06/12/2018, 15:25:22\n", "Output 3: 12 Jun, 2018\n", "Output 4: 12 June, 2018\n", "Output 5: 03PM\n" ] } ], "source": [ "# Example 2: Creating string from a timestamp\n", "\n", "from datetime import datetime\n", "\n", "timestamp = 1528797322\n", "date_time = datetime.fromtimestamp(timestamp)\n", "\n", "print(\"Date time object:\", date_time)\n", "\n", "d = date_time.strftime(\"%m/%d/%Y, %H:%M:%S\")\n", "print(\"Output 2:\", d)\t\n", "\n", "d = date_time.strftime(\"%d %b, %Y\")\n", "print(\"Output 3:\", d)\n", "\n", "d = date_time.strftime(\"%d %B, %Y\")\n", "print(\"Output 4:\", d)\n", "\n", "d = date_time.strftime(\"%I%p\")\n", "print(\"Output 5:\", d)\n", "\n", "# When you run the program, the output will be something like below:" ] }, { "cell_type": "markdown", "metadata": { "cell_style": "center" }, "source": [ "## Format Code List\n", "\n", "The table below shows all the codes that you can pass to the **`strftime()`** method.\n", "\n", "| Directive | Meaning | Example |\n", "|:----: |:---- |:---- |\n", "| **`%a`** | **Abbreviated weekday name.** | **Sun, Mon, ...** | \n", "| **`%A`** | **Full weekday name.** | **Sunday, Monday, ...** | \n", "| **`%w`** | **Weekday as a decimal number.** | **0, 1, ..., 6** | \n", "| **`%d`** | **Day of the month as a zero-padded decimal.** | **01, 02, ..., 31** | \n", "| **`%-d`** | **Day of the month as a decimal number.** | **1, 2, ..., 30** | \n", "| **`%b`** | **Abbreviated month name.** | **Jan, Feb, ..., Dec** | \n", "| **`%B`** | **Full month name.** | **January, February, ...** | \n", "| **`%m`** | **Month as a zero-padded decimal number.** | **01, 02, ..., 12** | \n", "| **`%-m`** | **Month as a decimal number.** | **1, 2, ..., 12** | \n", "| **`%y`** | **Year without century as a zero-padded decimal number.** | **00, 01, ..., 99** | \n", "| **`%-y`** | **Year without century as a decimal number.** | **0, 1, ..., 99** | \n", "| **`%Y`** | **Year with century as a decimal number.** | **2013, 2019 etc.** | \n", "| **`%H`** | **Hour (24-hour clock) as a zero-padded decimal number.** | **00, 01, ..., 23** | \n", "| **`%-H`** | **Hour (24-hour clock) as a decimal number.** | **0, 1, ..., 23** | \n", "| **`%I`** | **Hour (12-hour clock) as a zero-padded decimal number.** | **01, 02, ..., 12** | \n", "| **`%-I`** | **Hour (12-hour clock) as a decimal number.** | **1, 2, ... 12** | \n", "| **`%p`** | **Locale’s AM or PM.** | **AM, PM** | \n", "| **`%M`** | **Minute as a zero-padded decimal number.** | **00, 01, ..., 59** | \n", "| **`%-M`** | **Minute as a decimal number.** | **0, 1, ..., 59** | \n", "| **`%S`** | **Second as a zero-padded decimal number.** | **00, 01, ..., 59** | \n", "| **`%-S`** | **Second as a decimal number.** | **0, 1, ..., 59** | \n", "| **`%f`** | **Microsecond as a decimal number, zero-padded on the left.** | **000000 - 999999** | \n", "| **`%z`** | **UTC offset in the form +HHMM or -HHMM.** | | \n", "| **`%Z`** | **Time zone name.** | | \n", "| **`%j`** | **Day of the year as a zero-padded decimal number.** | **001, 002, ..., 366** | \n", "| **`%-j`** | **Day of the year as a decimal number.** | **1, 2, ..., 366** | \n", "| **`%U`** | **Week number of the year (Sunday as the first day of the week). All days in a new year preceding the first Sunday are considered to be in week 0.** | **00, 01, ..., 53** | \n", "| **`%U`** | **Week number of the year (Monday as the first day of the week). All days in a new year preceding the first Monday are considered to be in week 0.** | **00, 01, ..., 53** | \n", "| **`%c`** | **Locale’s appropriate date and time representation.** | **Mon Sep 30 07:06:05 2013** | \n", "| **`%x`** | **Locale’s appropriate date representation.** | **09/30/13** | \n", "| **`%X`** | **Locale’s appropriate time representation.** | **07:06:05** | \n", "| **`%%`** | **A literal '%' character.** | **%** | " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example 3: Locale's appropriate date and time" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "ExecuteTime": { "end_time": "2021-10-18T12:31:58.628277Z", "start_time": "2021-10-18T12:31:58.500841Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Output 1: Tue Jun 12 15:25:22 2018\n", "Output 2: 06/12/18\n", "Output 3: 15:25:22\n" ] } ], "source": [ "# Example 3: Locale's appropriate date and time\n", "\n", "from datetime import datetime\n", "\n", "timestamp = 1528797322\n", "date_time = datetime.fromtimestamp(timestamp)\n", "\n", "d = date_time.strftime(\"%c\")\n", "print(\"Output 1:\", d)\t\n", "\n", "d = date_time.strftime(\"%x\")\n", "print(\"Output 2:\", d)\n", "\n", "d = date_time.strftime(\"%X\")\n", "print(\"Output 3:\", d)\n", "\n", "# When you run the program, the output will be something like below:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ">**Note:** Format codes **`%c`**, **`%x`** and **`%X`** are used for locale's appropriate date and time representation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We also recommend you to check **[Python strptime()](https://github.com/milaan9/08_Python_Date_Time_Module/blob/main/003_Python_strptime%28%29.ipynb)**. The **`strptime()`** method creates a **`datetime`** object from a string." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "hide_input": false, "kernelspec": { "display_name": "Python 3", "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.8.8" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 2 }