YouTip LogoYouTip

Python Datetime

Python datetime Module | \n\n

Python 3.x Python datetime Module

\n \n

The datetime Module in Python

\n

The `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.

\n

Core 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
\n

Getting the Current Date and Time

\n

We can use the `now()` method of the `datetime` class to get the current date and time.

\n

Example

\nfrom datetime import datetime\n\n# Get the current date and time.\nnow = datetime.now()\nprint("Current time:", now)\n    

Output example:

\n

Current time: 2025-04-22 14:30:45.123456

\n

Create a specific date and time

\n

We can create a specific date and time using the constructor of the `datetime` class.

\n

Example

\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:

\n

Specific time: 2025-04-22 15:30:00

\n

Formatting Dates and Times

\n

The `datetime` object can be formatted as a string using the `strftime()` method.

\n

Example

\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:

\n

Formatted time: 2025-04-22 14:30:45

\n

Calculating Time Difference

\n

The `timedelta` class can be used to calculate the difference between two dates or times.

\n

Example

\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:

\n

Time 10 days later: 2025-05-02 14:30:45.123456

\n

Common use cases

\n

Calculate the number of days between two dates

\n

Example

\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:

\n

Difference in days between two dates: 9

\n

Handling Time Zones

\n

The `datetime` module does not directly support timezone operations itself, but timezones can be handled using the `pytz` library.

\n

Example

\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:

\n

Current time in Shanghai: 2025-04-22 14:30:45.123456+08:00

\n

Common Classes, Methods, and Attributes

\n

1. Core Classes

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ClassDescriptionExample
`datetime.date`Date class (year, month, day)date(2023, 5, 15)
`datetime.time`Time class (hours, minutes, seconds, microseconds)time(14, 30, 0)
`datetime.datetime`Date-time class (including date and time)datetime(2023, 5, 15, 14, 30)
`datetime.timedelta`Time interval class (used for date/time calculations)timedelta(days=5)
`datetime.tzinfo`Timezone information base class (requires subclassing for implementation)Custom timezone class
\n

2. Common methods/properties of `date` object

\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Method/PropertyDescriptionExample
`date.today()`Returns the current local datedate.today() β†’ date(2023, 5, 15)
`date.fromisoformat(str)`Parse a date from a `YYYY-MM-DD` stringdate.fromisoformat("2023-05-15")
`date.year`Year (read-only)d.year β†’ 2023
`date.month`Month (1-12, read-only)d.month β†’ 5
`date.day`Day (1-31, read-only)d.day β†’ 15
`date.weekday()`Returns the day of the week (0=Monday, 6=Sunday)d.weekday() β†’ 0
`date.isoformat()`Returns a string in `YYYY-MM-DD` formatd.isoformat() β†’ "2023-05-15"
`date.strftime(format)`Custom formatting outputd.strftime("%Y/%m/%d") β†’ "2023/05/15"
\n

3. Common methods/properties of the `time` object

\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Method/PropertyDescriptionExample
`time.hour`Hour (0-23, read-only)t.hour β†’ 14
`time.minute`minute (0-59, read-only)t.minute β†’ 30
`time.second`Second (0-59, read-only)t.second β†’ 0
`time.microsecond`Microsecond (0-999999, read-only)t.microsecond β†’ 0
`time.isoformat()`Returns a string in `HH:MM:SS.mmmmmm` formatt.isoformat() β†’ "14:30:00"
`time.strftime(format)`Custom formatted outputt.strftime("%H:%M") β†’ "14:30"
\n

4. Common Methods/Properties of `datetime` Object

\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Method/PropertyDescriptionExample
`datetime.now()`Returns the current local date and timedatetime.now() β†’ datetime(2023, 5, 15, 14, 30, 0)
`datetime.utcnow()`Returns the current UTC date and timedatetime.utcnow()
`datetime.fromtimestamp(ts)`Create a `datetime` object from a timestampdatetime.fromtimestamp(1684146600)
`datetime.timestamp()`Returns the timestamp (in floating-point seconds)dt.timestamp() β†’ 1684146600.0
`datetime.date()`Extract date partdt.date() β†’ date(2023, 5, 15)
`datetime.time()`Extract time partdt.time() β†’ time(14, 30)
`datetime.year`Year (same as `date`)dt.year β†’ 2023
`datetime.strftime(format)`Custom formatted outputdt.strftime("%Y-%m-%d %H:%M") β†’ "2023-05-15 14:30"
\n

5. Common Attributes of `timedelta` Object

\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n delta.seconds β†’ 3600(1 hour)\n \n \n \n \n \n \n \n
AttributeDescriptionExample
`days`Number of days (can be positive or negative)delta.days β†’ 5
`seconds`seconds (0-86399)
`microseconds`Microseconds (0-999999)delta.microseconds β†’ 0
\n

6. Common Format Specifiers (`strftime`)

\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SpecifierDescriptionExample Output
%YFour-digit year2023
%mTwo-digit month (01-12)05
%dTwo-digit day (01-31)15
%H24-hour hour (00-23)14
%Mminutes (00-59)30
%SSecond (00-59)00
%AFull weekday nameMonday
%aAbbreviated weekday nameMon
%BFull month nameMay
%bAbbreviated month nameMay
\n

Example

\n

1. Calculate Date Difference

\n

Example

\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

\n

Examples

\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)

\n

Examples

\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

\n

Examples

\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
  1. Immutability: All `datetime` objects are immutable; operations return new objects.
  2. \n
  3. Timezone Handling: Native `datetime` has no timezone support; you need to use `pytz` or `zoneinfo` from Python 3.9+.
  4. \n
  5. Performance: Frequently creating objects may affect performance; consider reusing or caching them.
  6. \n
  7. Boundary Checking: Invalid dates (e.g., `date(2023, 2, 30)`) will trigger a `ValueError`.
  8. \n
← Python CsvPython Stringio β†’