Python 3.x Python datetime Module
\n \nThe datetime Module in Python
\nThe `datetime` module in Python is the standard library module for handling dates and times. It provides various classes and functions that help us easily perform operations such as working with dates, times, and time differences. Whether it's getting the current time, formatting dates, or calculating time differences, the `datetime` module can handle it all.
\nCore Classes of the datetime Module
\n- \n
- `date` Class - The `date` class is used to represent dates and contains three attributes: year, month, and day. \n
- `time` Class - The `time` class is used to represent time and contains attributes such as hour, minute, second, and microsecond. \n
- `datetime` Class - The `datetime` class combines `date` and `time`, allowing it to represent both date and time simultaneously. \n
- `timedelta` Class - The `timedelta` class is used to represent time differences and can be used for addition and subtraction operations on dates and times. \n
Getting the Current Date and Time
\nWe can use the `now()` method of the `datetime` class to get the current date and time.
\nExample
\nfrom datetime import datetime\n\n# Get the current date and time.\nnow = datetime.now()\nprint("Current time:", now)\n Output example:
\nCurrent time: 2025-04-22 14:30:45.123456
\nCreate a specific date and time
\nWe can create a specific date and time using the constructor of the `datetime` class.
\nExample
\nfrom datetime import datetime\n\n# Create specific date and time\nspecific_time = datetime(2025, 4, 22, 15, 30, 0)\nprint("Specific time:", specific_time)\n Output Example:
\nSpecific time: 2025-04-22 15:30:00
\nFormatting Dates and Times
\nThe `datetime` object can be formatted as a string using the `strftime()` method.
\nExample
\nfrom datetime import datetime\n\n# Get current time\nnow = datetime.now()\n\n# Formatting Output\nformatted_time = now.strftime("%Y-%m-%d %H:%M:%S")\nprint("Format time:", formatted_time)\n Output Example:
\nFormatted time: 2025-04-22 14:30:45
\nCalculating Time Difference
\nThe `timedelta` class can be used to calculate the difference between two dates or times.
\nExample
\nfrom datetime import datetime, timedelta\n\n# Get current time\nnow = datetime.now()\n\n# Calculate time after 10 days\nfuture_time = now + timedelta(days=10)\nprint("10 Time after days:", future_time)\n Output example:
\nTime 10 days later: 2025-05-02 14:30:45.123456
\nCommon use cases
\nCalculate the number of days between two dates
\nExample
\nfrom datetime import date\n\n# Create two dates\ndate1 = date(2025, 4, 22)\ndate2 = date(2025, 5, 1)\n\n# Calculate day difference\ndelta = date2 - date1\nprint("Number of days between two dates:", delta.days)\n Output Example:
\nDifference in days between two dates: 9
\nHandling Time Zones
\nThe `datetime` module does not directly support timezone operations itself, but timezones can be handled using the `pytz` library.
\nExample
\nfrom datetime import datetime\nimport pytz\n\n# Get current timeand set the time zone\nnow = datetime.now(pytz.timezone('Asia/Shanghai'))\nprint("Current time in Shanghai:", now)\n Output Example:
\nCurrent time in Shanghai: 2025-04-22 14:30:45.123456+08:00
\nCommon Classes, Methods, and Attributes
\n1. Core Classes
\n| Class | \nDescription | \nExample | \n
|---|---|---|
| `datetime.date` | \nDate class (year, month, day) | \ndate(2023, 5, 15) | \n
| `datetime.time` | \nTime class (hours, minutes, seconds, microseconds) | \ntime(14, 30, 0) | \n
| `datetime.datetime` | \nDate-time class (including date and time) | \ndatetime(2023, 5, 15, 14, 30) | \n
| `datetime.timedelta` | \nTime interval class (used for date/time calculations) | \ntimedelta(days=5) | \n
| `datetime.tzinfo` | \nTimezone information base class (requires subclassing for implementation) | \nCustom timezone class | \n
2. Common methods/properties of `date` object
\n| Method/Property | \nDescription | \nExample | \n
|---|---|---|
| `date.today()` | \nReturns the current local date | \ndate.today() β date(2023, 5, 15) | \n
| `date.fromisoformat(str)` | \nParse a date from a `YYYY-MM-DD` string | \ndate.fromisoformat("2023-05-15") | \n
| `date.year` | \nYear (read-only) | \nd.year β 2023 | \n
| `date.month` | \nMonth (1-12, read-only) | \nd.month β 5 | \n
| `date.day` | \nDay (1-31, read-only) | \nd.day β 15 | \n
| `date.weekday()` | \nReturns the day of the week (0=Monday, 6=Sunday) | \nd.weekday() β 0 | \n
| `date.isoformat()` | \nReturns a string in `YYYY-MM-DD` format | \nd.isoformat() β "2023-05-15" | \n
| `date.strftime(format)` | \nCustom formatting output | \nd.strftime("%Y/%m/%d") β "2023/05/15" | \n
3. Common methods/properties of the `time` object
\n| Method/Property | \nDescription | \nExample | \n
|---|---|---|
| `time.hour` | \nHour (0-23, read-only) | \nt.hour β 14 | \n
| `time.minute` | \nminute (0-59, read-only) | \nt.minute β 30 | \n
| `time.second` | \nSecond (0-59, read-only) | \nt.second β 0 | \n
| `time.microsecond` | \nMicrosecond (0-999999, read-only) | \nt.microsecond β 0 | \n
| `time.isoformat()` | \nReturns a string in `HH:MM:SS.mmmmmm` format | \nt.isoformat() β "14:30:00" | \n
| `time.strftime(format)` | \nCustom formatted output | \nt.strftime("%H:%M") β "14:30" | \n
4. Common Methods/Properties of `datetime` Object
\n| Method/Property | \nDescription | \nExample | \n
|---|---|---|
| `datetime.now()` | \nReturns the current local date and time | \ndatetime.now() β datetime(2023, 5, 15, 14, 30, 0) | \n
| `datetime.utcnow()` | \nReturns the current UTC date and time | \ndatetime.utcnow() | \n
| `datetime.fromtimestamp(ts)` | \nCreate a `datetime` object from a timestamp | \ndatetime.fromtimestamp(1684146600) | \n
| `datetime.timestamp()` | \nReturns the timestamp (in floating-point seconds) | \ndt.timestamp() β 1684146600.0 | \n
| `datetime.date()` | \nExtract date part | \ndt.date() β date(2023, 5, 15) | \n
| `datetime.time()` | \nExtract time part | \ndt.time() β time(14, 30) | \n
| `datetime.year` | \nYear (same as `date`) | \ndt.year β 2023 | \n
| `datetime.strftime(format)` | \nCustom formatted output | \ndt.strftime("%Y-%m-%d %H:%M") β "2023-05-15 14:30" | \n
5. Common Attributes of `timedelta` Object
\n| Attribute | \nDescription | \nExample | \n
|---|---|---|
| `days` | \nNumber of days (can be positive or negative) | \ndelta.days β 5 | \n
| `seconds` | \nseconds (0-86399) | |
| `microseconds` | \nMicroseconds (0-999999) | \ndelta.microseconds β 0 | \n
6. Common Format Specifiers (`strftime`)
\n| Specifier | \nDescription | \nExample Output | \n
|---|---|---|
| %Y | \nFour-digit year | \n2023 | \n
| %m | \nTwo-digit month (01-12) | \n05 | \n
| %d | \nTwo-digit day (01-31) | \n15 | \n
| %H | \n24-hour hour (00-23) | \n14 | \n
| %M | \nminutes (00-59) | \n30 | \n
| %S | \nSecond (00-59) | \n00 | \n
| %A | \nFull weekday name | \nMonday | \n
| %a | \nAbbreviated weekday name | \nMon | \n
| %B | \nFull month name | \nMay | \n
| %b | \nAbbreviated month name | \nMay | \n
Example
\n1. Calculate Date Difference
\nExample
\nfrom datetime import date, timedelta\n\nd1 = date(2023, 5, 15)\nd2 = date(2023, 6, 1)\ndelta = d2 - d1 # Return timedelta object\nprint(delta.days) # Output: 17\n \n 2. Time addition and subtraction
\nExamples
\n\nfrom datetime import datetime, timedelta\n\nnow = datetime.now()\nfuture = now + timedelta(days=3, hours=2)\nprint(future.strftime("%Y-%m-%d %H:%M"))\n \n 3. Time zone conversion (need to install pytz)
\nExamples
\n\nfrom datetime import datetime\nimport pytz\n\nutc_time = datetime.utcnow().replace(tzinfo=pytz.utc)\nbeijing_time = utc_time.astimezone(pytz.timezone("Asia/Shanghai"))\nprint(beijing_time)\n \n 4. Parse string
\nExamples
\n\nfrom datetime import datetime\n\ndt = datetime.strptime("2023-05-15 14:30", "%Y-%m-%d %H:%M")\nprint(dt.year) # Output: 2023\n Notes
\n- \n
- Immutability: All `datetime` objects are immutable; operations return new objects. \n
- Timezone Handling: Native `datetime` has no timezone support; you need to use `pytz` or `zoneinfo` from Python 3.9+. \n
- Performance: Frequently creating objects may affect performance; consider reusing or caching them. \n
- Boundary Checking: Invalid dates (e.g., `date(2023, 2, 30)`) will trigger a `ValueError`. \n
YouTip