{"id":6926,"date":"2026-01-25T17:59:36","date_gmt":"2026-01-25T17:59:36","guid":{"rendered":"https:\/\/www.askpython.com\/?p=6926"},"modified":"2026-01-25T18:12:35","modified_gmt":"2026-01-25T18:12:35","slug":"python-datetime-module","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/python-datetime-module","title":{"rendered":"Python datetime module guide"},"content":{"rendered":"<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import datetime\n\n# Get current date and time\nnow = datetime.now()\nprint(now)  # 2026-01-25 14:30:45.123456\n\n# Create a specific datetime object\nspecific_date = datetime(2026, 1, 25, 14, 30, 45)\nprint(specific_date)  # 2026-01-25 14:30:45\n<\/pre><\/div>\n\n\n<p>Python&#8217;s datetime module handles date and time operations through five core classes. The datetime.datetime class represents a specific point in time with year, month, day, hour, minute, second, and microsecond precision. <\/p>\n\n\n\n<p>The date class stores calendar dates without time information. The time class holds time values independent of dates. The timedelta class measures durations between two points in time. The tzinfo class provides timezone information for aware datetime objects.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Creating Python datetime objects<\/h2>\n\n\n\n<p>The datetime constructor accepts integer arguments in descending order of significance. Year, month, and day are required parameters. Hour, minute, second, and microsecond default to zero when omitted.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import datetime, date, time\n\n# Full datetime with all components\ndt = datetime(2026, 1, 25, 14, 30, 45, 500000)\nprint(dt)  # 2026-01-25 14:30:45.500000\n\n# Date only\nd = date(2026, 1, 25)\nprint(d)  # 2026-01-25\n\n# Time only\nt = time(14, 30, 45)\nprint(t)  # 14:30:45\n\n<\/pre><\/div>\n\n\n<p>The now() method retrieves the current local datetime. The today() method returns the current date. The utcnow() method provides the current UTC datetime without timezone information.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import datetime, date\n\ncurrent_datetime = datetime.now()\ncurrent_date = date.today()\nutc_time = datetime.utcnow()\n\nprint(f&quot;Local: {current_datetime}&quot;)\nprint(f&quot;Date: {current_date}&quot;)\nprint(f&quot;UTC: {utc_time}&quot;)\n\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Extracting Python datetime components<\/h2>\n\n\n\n<p>Datetime objects expose individual components as attributes. Access year, month, day, hour, minute, second, and microsecond directly from any datetime instance.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import datetime\n\ndt = datetime(2026, 1, 25, 14, 30, 45)\n\nprint(dt.year)        # 2026\nprint(dt.month)       # 1\nprint(dt.day)         # 25\nprint(dt.hour)        # 14\nprint(dt.minute)      # 30\nprint(dt.second)      # 45\nprint(dt.weekday())   # 6 (Sunday)\n\n<\/pre><\/div>\n\n\n<p>The weekday() method returns integers from 0 (Monday) to 6 (Sunday). The isoweekday() method uses 1 (Monday) through 7 (Sunday) instead.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Formatting Python datetime with strftime()<\/h2>\n\n\n\n<p>The strftime() method converts datetime objects into formatted strings. Format codes specify how to represent each component. Common codes include %Y for four-digit year, %m for zero-padded month, %d for zero-padded day, %H for 24-hour format hour, and %M for minute.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import datetime\n\ndt = datetime(2026, 1, 25, 14, 30, 45)\n\n# Different format patterns\nprint(dt.strftime(&quot;%Y-%m-%d&quot;))              # 2026-01-25\nprint(dt.strftime(&quot;%B %d, %Y&quot;))             # January 25, 2026\nprint(dt.strftime(&quot;%m\/%d\/%Y %H:%M:%S&quot;))     # 01\/25\/2026 14:30:45\nprint(dt.strftime(&quot;%I:%M %p&quot;))              # 02:30 PM\nprint(dt.strftime(&quot;%A, %B %d, %Y&quot;))         # Sunday, January 25, 2026\n\n<\/pre><\/div>\n\n\n<p>Use %A for full weekday name, %B for full month name, %I for 12-hour format, and %p for AM\/PM designation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Parsing strings with strptime()<\/h2>\n\n\n\n<p>The strptime() method converts string representations into datetime objects. The format string must match the input string&#8217;s structure exactly.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import datetime\n\ndate_string = &quot;2026-01-25 14:30:45&quot;\ndt = datetime.strptime(date_string, &quot;%Y-%m-%d %H:%M:%S&quot;)\nprint(dt)  # 2026-01-25 14:30:45\n\n# Parsing different formats\ndate1 = datetime.strptime(&quot;January 25, 2026&quot;, &quot;%B %d, %Y&quot;)\ndate2 = datetime.strptime(&quot;25\/01\/2026&quot;, &quot;%d\/%m\/%Y&quot;)\ndate3 = datetime.strptime(&quot;2026-W04-7&quot;, &quot;%Y-W%W-%w&quot;)\n\nprint(date1)  # 2026-01-25 00:00:00\nprint(date2)  # 2026-01-25 00:00:00\nprint(date3)  # 2026-01-25 00:00:00\n\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Working with timedelta<\/h2>\n\n\n\n<p>Timedelta objects represent the difference between two datetime values. You can add or subtract timedelta from datetime objects to perform date arithmetic.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import datetime, timedelta\n\ndt = datetime(2026, 1, 25, 14, 30)\n\n# Add time\nfuture = dt + timedelta(days=7, hours=3, minutes=15)\nprint(future)  # 2026-02-01 17:45:00\n\n# Subtract time\npast = dt - timedelta(weeks=2, days=3)\nprint(past)  # 2026-01-04 14:30:00\n\n# Calculate difference between dates\ndate1 = datetime(2026, 1, 25)\ndate2 = datetime(2026, 2, 15)\ndifference = date2 - date1\nprint(difference.days)  # 21\nprint(difference.total_seconds())  # 1814400.0\n\n<\/pre><\/div>\n\n\n<p>Timedelta accepts days, seconds, microseconds, milliseconds, minutes, hours, and weeks as arguments. Internal storage uses only days, seconds, and microseconds for precision.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Timezone handling with Python datetime<\/h2>\n\n\n\n<p>The datetime module provides basic timezone support through the timezone class. For production applications, use the zoneinfo module (Python 3.9+) or pytz library for comprehensive timezone handling.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import datetime, timezone, timedelta\n\n# Create timezone-aware datetime\nutc = timezone.utc\ndt_utc = datetime(2026, 1, 25, 14, 30, tzinfo=utc)\nprint(dt_utc)  # 2026-01-25 14:30:00+00:00\n\n# Custom timezone offset\nest = timezone(timedelta(hours=-5))\ndt_est = datetime(2026, 1, 25, 9, 30, tzinfo=est)\nprint(dt_est)  # 2026-01-25 09:30:00-05:00\n\n# Convert between timezones\ndt_converted = dt_utc.astimezone(est)\nprint(dt_converted)  # 2026-01-25 09:30:00-05:00\n\n<\/pre><\/div>\n\n\n<p>Using pytz for more complex timezone operations:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom datetime import datetime\nimport pytz\n\n# Define timezones\nny_tz = pytz.timezone(&#039;America\/New_York&#039;)\ntokyo_tz = pytz.timezone(&#039;Asia\/Tokyo&#039;)\n\n# Create timezone-aware datetime\nny_time = ny_tz.localize(datetime(2026, 1, 25, 9, 30))\nprint(ny_time)  # 2026-01-25 09:30:00-05:00\n\n# Convert to Tokyo time\ntokyo_time = ny_time.astimezone(tokyo_tz)\nprint(tokyo_time)  # 2026-01-25 23:30:00+09:00\n\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Integrating Python datetime with pandas groupby<\/h2>\n\n\n\n<p>Pandas extends datetime functionality for data analysis through the dt accessor. This accessor provides methods to extract datetime components and enables grouping operations on time-based data.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport pandas as pd\nfrom datetime import datetime, timedelta\n\n# Create sample dataframe with datetime\ndates = pd.date_range(start=&#039;2026-01-01&#039;, periods=100, freq=&#039;D&#039;)\ndf = pd.DataFrame({\n    &#039;date&#039;: dates,\n    &#039;sales&#039;: range(100, 200),\n    &#039;region&#039;: &#x5B;&#039;North&#039;, &#039;South&#039;, &#039;East&#039;, &#039;West&#039;] * 25\n})\n\n# Extract datetime components\ndf&#x5B;&#039;year&#039;] = df&#x5B;&#039;date&#039;].dt.year\ndf&#x5B;&#039;month&#039;] = df&#x5B;&#039;date&#039;].dt.month\ndf&#x5B;&#039;day_of_week&#039;] = df&#x5B;&#039;date&#039;].dt.dayofweek\ndf&#x5B;&#039;week&#039;] = df&#x5B;&#039;date&#039;].dt.isocalendar().week\n\nprint(df.head())\n\n<\/pre><\/div>\n\n\n<p>The pandas groupby operation combined with datetime enables powerful time-based aggregations. Group data by any datetime component using the dt accessor.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Group by month and calculate total sales\nmonthly_sales = df.groupby(df&#x5B;&#039;date&#039;].dt.month)&#x5B;&#039;sales&#039;].sum()\nprint(monthly_sales)\n\n# Group by day of week\nweekday_sales = df.groupby(df&#x5B;&#039;date&#039;].dt.dayofweek)&#x5B;&#039;sales&#039;].mean()\nprint(weekday_sales)\n\n# Multiple grouping with datetime and other columns\nregion_month = df.groupby(&#x5B;df&#x5B;&#039;date&#039;].dt.month, &#039;region&#039;])&#x5B;&#039;sales&#039;].sum()\nprint(region_month)\n\n<\/pre><\/div>\n\n\n<p>The pd.Grouper class provides more control over datetime grouping operations. Use the freq parameter to specify grouping frequency like daily (D), weekly (W), monthly (M), or yearly (Y).<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Group by week using pd.Grouper\nweekly_sales = df.groupby(pd.Grouper(key=&#039;date&#039;, freq=&#039;W&#039;))&#x5B;&#039;sales&#039;].sum()\nprint(weekly_sales)\n\n# Group by month with custom aggregations\nmonthly_stats = df.groupby(pd.Grouper(key=&#039;date&#039;, freq=&#039;M&#039;)).agg({\n    &#039;sales&#039;: &#x5B;&#039;sum&#039;, &#039;mean&#039;, &#039;max&#039;, &#039;min&#039;]\n})\nprint(monthly_stats)\n\n# Combine pd.Grouper with other grouping columns\nregion_weekly = df.groupby(&#x5B;\n    pd.Grouper(key=&#039;date&#039;, freq=&#039;W&#039;),\n    &#039;region&#039;\n])&#x5B;&#039;sales&#039;].sum()\nprint(region_weekly)\n\n<\/pre><\/div>\n\n\n<p>Resample provides another approach for time-based grouping. This method works specifically with DatetimeIndex objects and offers identical functionality to pd.Grouper with cleaner syntax.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Set datetime as index for resampling\ndf_indexed = df.set_index(&#039;date&#039;)\n\n# Resample to weekly frequency\nweekly_resample = df_indexed.resample(&#039;W&#039;)&#x5B;&#039;sales&#039;].sum()\nprint(weekly_resample)\n\n# Resample to monthly with multiple aggregations\nmonthly_resample = df_indexed.resample(&#039;M&#039;).agg({\n    &#039;sales&#039;: &#x5B;&#039;sum&#039;, &#039;mean&#039;],\n    &#039;region&#039;: &#039;first&#039;\n})\nprint(monthly_resample)\n\n<\/pre><\/div>\n\n\n<p>For more complex time series analysis, combine datetime operations with rolling windows and pandas groupby.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Calculate 7-day rolling average by region\ndf_indexed&#x5B;&#039;rolling_avg&#039;] = (\n    df_indexed.groupby(&#039;region&#039;)&#x5B;&#039;sales&#039;]\n    .transform(lambda x: x.rolling(window=7, min_periods=1).mean())\n)\n\n# Group by month and calculate statistics on rolling values\nmonthly_rolling = df_indexed.groupby(df_indexed.index.month).agg({\n    &#039;sales&#039;: &#039;sum&#039;,\n    &#039;rolling_avg&#039;: &#039;mean&#039;\n})\nprint(monthly_rolling)\n\n<\/pre><\/div>\n\n\n<p>The datetime module handles date arithmetic, formatting, and parsing operations. Pandas extends these capabilities for data analysis through the dt accessor and groupby operations. Together, they provide comprehensive tools for time-based data manipulation and aggregation. Use datetime for individual date operations and pandas groupby for analyzing time series datasets at scale.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python&#8217;s datetime module handles date and time operations through five core classes. The datetime.datetime class represents a specific point in time with year, month, day, hour, minute, second, and microsecond precision. The date class stores calendar dates without time information. The time class holds time values independent of dates. The timedelta class measures durations between [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":7010,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-6926","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-modules"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/6926","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=6926"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/6926\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/7010"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=6926"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=6926"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=6926"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}