The datetime Module
The datetime module provides classes for manipulating dates and times in various ways. While the standard representation of time is supported, there is a greater emphasis on the ease of manipulating dates, times, and their components. The classes provided by the datetime module include:
datetime.date (year, month, day)
Standard date. Attributes: year, month, day. Immutable object.
import datetime
d = datetime.date(2012, 12, 14)
print(d.year) # 2012
print(d.day) # 14
print(d.month) # 12
datetime.datetime (year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Contains all the information of datetime.date objects plus datetime.time.
import datetime
a = datetime.datetime(2017, 3, 5)
print(a) # datetime.datetime(2017, 3, 5, 0, 0)
b = datetime.datetime(2017, 3, 5, 12, 30, 10)
print(b) # datetime.datetime(2017, 3, 5, 12, 30, 10)
d = datetime.datetime(2017, 3, 5, 12, 30, 10)
print(d.year) # 2017
print(d.second) # 10
print(d.hour) # 12
datetime.datetime accepts several additional arguments: year, month, day, hour, minute, and second. It also allows specifying information about microseconds and time zones.
datetime.time (hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Standard time, independent of date. Attributes: hour, minute, second, microsecond, tzinfo.
datetime.timedelta
Describes a specific duration in time, which is the difference between two distinct moments.
| Attribute | Value |
|---|---|
| days | Between −999999999 and 999999999 inclusive |
| seconds | Between 0 and 86399 inclusive |
| microseconds | Between 0 and 999999 inclusive |
Supported Operations
| Operation | Result |
|---|---|
| t1 = t2 + t3 | Adds the delta between dates |
| t1 = t2 — t3 | Difference of deltas between dates |
| t1 = t2 * i or t1 = i * t2 | Multiplies the delta by an integer |
| t1 = t2 * f or t1 = f * t2 | Delta is multiplied by a floating-point number |
| f = t2 / t3 | Divides the total duration t2 by interval t3. Returns a floating-point object |
| t1 = t2 / f or t1 = t2 / i | Delta is divided by a floating-point number or integer |
| t1 = t2% t3 | Remainder part is calculated as a timedelta object |
| q, r = divmod (t1, t2) | Calculates quotient and remainder: q = t1 // t2 and r = t1% t2. q is an integer, and r is a timedelta object |
| +t1 | Returns a timedelta object with an identical value to t1 |
| -t1 | Returns a timedelta object with the opposite value to t1 |
| abs (t) | Returns a timedelta object with positive values for all properties of t |
| str (t) | Returns a string representation of object t in the default format |
| repr (t) | Returns a string representation of object t in a format with negative values |
timedelta.total_seconds ()
Returns the total number of seconds contained in the duration. Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 * 6) / 10 * 6 calculated with true division enabled. Example:
from datetime import timedelta
year = timedelta(days=365)
another_year = timedelta(weeks=40, days=84, hours=23, minutes=50, seconds=600) # adds up to 365 days
print(year.total_seconds()) # 31536000.0
print(year == another_year) # True
ten_years = 10 * year
print(ten_years, ten_years.days // 365) # (datetime.timedelta(days=3650), 10)
nine_years = ten_years - year
print(nine_years, nine_years.days // 365) # (datetime.timedelta(days=3285), 9)
three_years = nine_years // 3
print(three_years, three_years.days // 365) # (datetime.timedelta(days=1095), 3)
print(abs(three_years - ten_years) == 2 * three_years + year) # True
datetime.tzinfo
Abstract base class for time zone information (e.g., for accounting for time zones and/or daylight saving time).
Class Methods of datetime:
datetime.combine (date, time)
datetime object from the combination of date and time objects.
datetime.fromtimestamp (timestamp)
Date from the standard time representation.
datetime.fromordinal (ordinal)
Date from a number representing the number of days since 01.01.1970.
datetime.now (tz=None)
datetime object from the current date and time.
datetime.today ()
datetime object from the current date and time. Works the same as datetime.now() with tz=None.
datetime.strptime (date_string, format)
Converts a string to datetime according to the format.
| Format | Value |
|---|---|
| %a | Abbreviated weekday name |
| %A | Full weekday name |
| %b | Abbreviated month name |
| %B | Full month name |
| %c | Date and time |
| %d | Day of the month 01,31 |
| %H | Hour (24-hour format) 00,23 |
| %I | Hour (12-hour format) 01,12 |
| %j | Day of the year 001,366 |
| %m | Month number 01,12 |
| %M | Minute number 00,59 |
| %p | AM or PM (in 12-hour format) |
| %S | Second number 00,61 |
| %U | Week number of the year (week 0 starts on Sunday) 00,53 |
| %w | Day of the week number 0(Sunday), 6 |
| %W | Week number of the year (week 0 starts on Monday) 00,53 |
| %x | Date |
| %X | Time |
| %y | Year without century 00,99 |
| %Y | Year with century |
| %Z | Time zone |
| %% | '%' character |
datetime.strftime (format)
Converts datetime to a string according to the format.
| Format | Value |
|---|---|
| %a | Abbreviated weekday name |
| %A | Full weekday name |
| %b | Abbreviated month name |
| %B | Full month name |
| %c | Date and time |
| %d | Day of the month 01,31 |
| %H | Hour (24-hour format) 00,23 |
| %I | Hour (12-hour format) 01,12 |
| %j | Day of the year 001,366 |
| %m | Month number 01,12 |
| %M | Minute number 00,59 |
| %p | AM or PM (in 12-hour format) |
| %S | Second number 00,61 |
| %U | Week number of the year (week 0 starts on Sunday) 00,53 |
| %w | Day of the week number 0(Sunday), 6 |
| %W | Week number of the year (week 0 starts on Monday) 00,53 |
| %x | Date |
| %X | Time |
| %y | Year without century 00,99 |
| %Y | Year with century |
| %Z | Time zone |
| %% | '%' character |
datetime.date ()
Date object (with time truncated).
datetime.isoweekday ()
Day of the week as a number, Monday is 1, Sunday is 7.
datetime.isocalendar ()
Tuple (ISO year, ISO week number, ISO weekday).
datetime.isoformat (sep='T')
A nicely formatted string like “YYYY-MM-DDTHH: MM: SS.mmmmmm” or, if microsecond == 0, “YYYY-MM-DDTHH: MM: SS”.
datetime.replace ([year[, month[, day[, hour, minute, second, microsecond, tzinfo]]]])
Returns a new datetime object with modified attributes.
datetime.time ()
Time object (with date truncated).
datetime.timetuple ()
Returns struct_time from datetime.
datetime.timestamp ()
Returns the time in seconds since the epoch.
datetime.toordinal ()
Number of days since 01.01.1970.
datetime.weekday ()
Day of the week as a number, Monday is 0, Sunday is 6.
Supported Operations:
| Operation | Result |
|---|---|
| datetime2 = datetime1 + timedelta | Adds the specified period to the date |
| datetime2 = datetime1 — timedelta | Subtracts the specified period from the date |
| timedelta = datetime1 — datetime2 | Returns the difference between two dates |
| datetime1 < datetime2 | Compares date and time |