- Module presentation
- Basic types
- Aware and Naive instances
- Create date, time and datetime
- Create a datetime from a timestamp
- Date formatting
- Date computation
- Date comparison
date, time and datetime
Modules
datetime module : classes for manipulating dates and times.
dateutil module : third-party library with expanded time zone and parsing support.
pytz module : Before Python 3.9, it is highly recommended.
Third-party with accurate and cross platform timezone types and calculations (Python 2.4 or higher required).
It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference
(datetime.tzinfo).
Basic types
These are immutables.
class datetime.date
Naive date relying only the current Gregorian calendar.
Attributes: year, month, and day.
class datetime.time
A time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds.
There is no notion of “leap seconds” here.
Attributes: hour, minute, second, microsecond, and tzinfo.
class datetime.datetime
A combination of a date and a time.
Attributes: year, month, day, hour, minute, second, microsecond, and tzinfo.
class datetime.timedelta
A duration expressing the difference between two date, time, or datetime instances to microsecond resolution.
class datetime.tzinfo
An abstract base class for time zone information objects.
These are used by the datetime and time classes to provide the timezone information
class datetime.timezone
A class that implements the tzinfo abstract base class as a fixed offset from the UTC.
Subclass relationships:
object timedelta tzinfo timezone time date datetime |
Aware and Naive instances
datetime
and time
objects may be aware or naive of the timezone information.
It is up to the developer to specify or not that thanks to the tzinfo
field.
In practice : aware flavor is only good for datetime type. Indeed time
type is error-prone because of savelights.
Create date, time and datetime
from datetime import datetime, time, date from datetime import timezone import pytz from pytz.tzinfo import DstTzInfo def create_a_date(): christmas_date: date = date(2010, 12, 25) print(f"christmas = {christmas_date}") # christmas = 2010-12-25 def create_a_naive_time(): time_15hours_45minutes_30_seconds: time = time(15, 45, 30) print(f"time naive = {time_15hours_45minutes_30_seconds}") # time naive = 15:45:30 def create_a_naive_datetime(): christmas_datetime: datetime = datetime(2010, 12, 25) print(f"christmas = {christmas_datetime}") # chrisstmas = 2010-12-25 00:00:00 christmas_datetime: datetime = datetime(2010, 12, 25, 0, 1, 30) print(f"christmas with a time= {christmas_datetime}") # christmas = 2010-12-25 00:01:30 def create_a_aware_datetime(): christmas_utc_datetime: datetime = datetime(2010, 12, 25, tzinfo=timezone.utc) print(f"christmas utc= {christmas_utc_datetime}") # christmas utc = 2010-12-25 00:00:00+00:00 # with pytz timezone_paris: DstTzInfo = \ pytz.timezone("Europe/Paris") christmas_paris_datetime: datetime = timezone_paris.localize(datetime(2010, 12, 25, 0, 1, 30)) print(f"christmas paris= {christmas_paris_datetime}") # christmas paris = 2010-12-25 00:01:30+01:00 timezone_us_eastern: DstTzInfo = pytz.timezone("US/Eastern") christmas_us_eastern_datetime: datetime = timezone_us_eastern.localize( datetime(2010, 12, 25, 0, 1, 30)) print(f"christmas us eastern= {christmas_us_eastern_datetime}") # christmas us eastern= 2010-12-25 00:01:30-05:00 |
Output:
create_a_date() christmas = 2010-12-25 ---------- create_a_naive_datetime() christmas = 2010-12-25 00:00:00 christmas with a time= 2010-12-25 00:01:30 ---------- create_a_aware_datetime() christmas utc= 2010-12-25 00:00:00+00:00 christmas paris= 2010-12-25 00:01:30+01:00 christmas us eastern= 2010-12-25 00:01:30-05:00 |
Create a datetime from a timestamp
from datetime import datetime, timezone import pytz def create_a_datetime_from_timestamp(): timestamp_in_seconds_now: int = int(datetime.now().timestamp()) print(f'timestamp_in_seconds_now={timestamp_in_seconds_now}') # timestamp_in_seconds_now=1681551053 # fromtimestamp expects as unit seconds (posix way) now_utc_datetime = datetime.fromtimestamp(datetime.now().timestamp(), tz=timezone.utc) print(f"now_utc_datetime= {now_utc_datetime}") # now_utc_datetime= 2023-04-15 09:30:53.822828+00:00 # fromtimestamp with a variable as unit ms. We need to convert in seconds # 1636106414715 -> 5 nov 2021 11h00 paris foo_datetime_ms = 1636106414715 foo_utc_datetime = datetime.fromtimestamp(foo_datetime_ms / 1000.0, tz=timezone.utc) print(f"foo_utc_datetime = {foo_utc_datetime}") # foo_utc_datetime = 2021-11-05 10:00:14.715000+00:00 foo_paris_datetime = datetime.fromtimestamp(foo_datetime_ms / 1000.0, pytz.timezone("Europe/Paris")) print(f"foo_paris_datetime = {foo_paris_datetime}") # foo_paris_datetime= 2021-11-05 11:00:14.715000+01:00 foo_naive_datetime = datetime.fromtimestamp(foo_datetime_ms / 1000.0) print(f"foo_naive_datetime= {foo_naive_datetime}") # foo_naive_datetime = 2021-11-05 11:00:14.7150006) |
Output:
timestamp_in_seconds_now=1681551053 now_utc_datetime= 2023-04-15 09:30:53.822828+00:00 foo_utc_datetime = 2021-11-05 10:00:14.715000+00:00 foo_paris_datetime = 2021-11-05 11:00:14.715000+01:00 foo_naive_datetime= 2021-11-05 11:00:14.715000 |
Date formatting
from datetime import datetime def convert_string_into_datetime(): christmas_datetime: datetime = datetime.strptime('25/12/2010 00:01:30', '%d/%m/%Y %H:%M:%S') print(f"christmas_datetime = {christmas_datetime}") # christmas_datetime = 2010-12-25 00:01:30 def convert_datetime_into_string(): christmas_datetime: datetime = datetime(2010, 12, 25, 0, 1, 30) christmas_str: str = datetime.strftime(christmas_datetime, '%d/%m/%Y %H:%M:%S') print(f"christmas_str = {christmas_str}") # christmas_str = 25/12/2010 00:01:30 |
Output:
convert_string_into_datetime() christmas_datetime = 2010-12-25 00:01:30 ---------- convert_datetime_into_string() christmas_str = 25/12/2010 00:01:30 |
Date computation
Currently, we have two main ways to perform date computations in Python.
– The first way is not bad, but may be limited: that is the built-in and official datetime library: timedelta(). It accepts as argument a duration
unit key: days, seconds, weeks, hours, minutes, milliseconds, microseconds
.
We can add or subtract timedelta to a datetime object.
– The other way is a third-party library: dateutil.relativedelta
.
it provides more unit of time and also completes the official datetime Library by providing in addition to the plural form, the singular form that REPLACES
the corresponding value.
It accepts as argument a duration
unit key(not exhaustive): days, seconds, weeks, hours, minutes, milliseconds, microseconds,months,year,
and the singular form: day, second, weekday, hour, minute, millisecond, microsecond,
.
Example:
from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta def compute_some_dates_with_dateutil_relativedelta(): print("today = " + str(datetime.today())) # today = 2021-11-05 12:25:47.615337 today_minus_4_days: datetime = datetime.today() - relativedelta(days=4) print("today - 4 days = " + str(today_minus_4_days)) # today - 4 days = 2021-11-01 12:25:47.615345 today_plus_4_days: datetime = datetime.today() + relativedelta(days=4) print("today + 4 days = " + str(today_plus_4_days)) # today + 4 days = 2021-11-09 12:25:47.615462 today_minus_120_seconds: datetime = datetime.today() - relativedelta(seconds=120) print("today - 120 seconds= " + str(today_minus_120_seconds)) # today - 120 seconds = 2021-10-05 12:25:47.615420 today_plus_120_seconds: datetime = datetime.today() + relativedelta(seconds=120) print("today + 120 seconds= " + str(today_plus_120_seconds)) # today + 120 seconds = 2021-10-05 12:25:47.615420 print(f'Other way to use the relativedelta() function: with the singular form that ' f'does not perform an arithmetic; operation, but rather REPLACES the corresponding value.') today_set_day_to_15: datetime = datetime.today() - relativedelta(day=15) print("today_set_day_to_15=" + str(today_set_day_to_15)) # today_set_day_to_15=2023-04-15 10:37:17.448909 today_set_month_to_12: datetime = datetime.today() - relativedelta(month=12) print("today_set_month_to_12=" + str(today_set_month_to_12)) # today_set_month_to_12=2023-12-17 10:37:17.448909 def compute_some_dates_with_datetime_timedelta(): print("today = " + str(datetime.today())) # today = 2021-11-05 12:25:47.615337 today_minus_4_days: datetime = datetime.today() - timedelta(days=4) print("today - 4 days = " + str(today_minus_4_days)) # today - 4 days = 2021-11-01 12:25:47.615345 today_plus_4_days: datetime = datetime.today() + timedelta(days=4) print("today + 4 days = " + str(today_plus_4_days)) # today + 4 days = 2021-11-09 12:25:47.615462 today_minus_120_seconds: datetime = datetime.today() - timedelta(seconds=120) print("today - 120 seconds= " + str(today_minus_120_seconds)) # today - 120 seconds = 2021-10-05 12:25:47.615420 today_plus_120_seconds: datetime = datetime.today() + timedelta(seconds=120) print("today + 120 seconds= " + str(today_plus_120_seconds)) # today + 120 seconds = 2021-10-05 12:25:47.615420 print(f'compute_some_dates_with_dateutil_relativedelta()') compute_some_dates_with_dateutil_relativedelta() print(f'----------') print(f'compute_some_dates_with_datetime_timedelta()') compute_some_dates_with_datetime_timedelta() |
Output:
compute_some_dates_with_dateutil_relativedelta() today = 2023-04-17 11:25:20.726294 today - 4 days = 2023-04-13 11:25:20.726294 today + 4 days = 2023-04-21 11:25:20.726294 today - 120 seconds= 2023-04-17 11:23:20.726294 today + 120 seconds= 2023-04-17 11:27:20.726294 Other way to use the relativedelta() function: with the singular form that does not perform an arithmetic; operation, but rather REPLACES the corresponding value. today_set_day_to_15=2023-04-15 11:25:20.726294 today_set_month_to_12=2023-12-17 11:25:20.726294 ---------- compute_some_dates_with_datetime_timedelta() today = 2023-04-17 11:25:20.726294 today - 4 days = 2023-04-13 11:25:20.726294 today + 4 days = 2023-04-21 11:25:20.726294 today - 120 seconds= 2023-04-17 11:23:20.726294 today + 120 seconds= 2023-04-17 11:27:20.726294 |
Date comparison
from datetime import datetime def compare_dates(): older_datetime: datetime = datetime(2010, 12, 25) newer_datetime: datetime = datetime(2010, 12, 26) is_newer_more_recent = newer_datetime > older_datetime print(f"is_newer_more_recent = {is_newer_more_recent}") # is_newer_more_recent = True is_newer_less_recent = newer_datetime < older_datetime print(f"is_newer_less_recent = {is_newer_less_recent}") # is_newer_less_recent = False |
Output:
compare_dates() is_newer_more_recent = True is_newer_less_recent = False |