Python

Write an awesome doc for Python. A very nice an practical one extracted from Python official documentation.

View on GitHub

datetime Module

date Class

import datetime
birthdate = datetime.date(2005, 1, 1) # Year, Month, Day
print(birthdate)

[!TIP]

When coding and developing modules in Python try to avoid giving the same name to a class as your module since it can be quite confusing. Like what you can see here, datatime.datetime!

Learn more about naming conventions in Python here. This is supper important since if you pick a bad name it will be hard to change later and also it became a tech debt which its interest rate will grow over time.

strftime

from datetime import date
birthdate = date(2004, 12, 20)
print(birthdate.strftime("%Y.%m.%d"))  # 2004.12.20
print(f"{birthdate.year}.{birthdate.month}.{birthdate.day}")

[!INFO]

You can thank C programmers who have the religious belief that you only get so many vowels in your lifetime; the more vowels they type, the sooner they will die. Yes, it is string-format-time, and strptime is string-parse-time. Why the methods were not simply named “time_to_string” and “time_from_string” like sensible people would do is beyond understanding.

Ref

Getting The Current Date & Time

now today utcnow
```py from datetime import datetime print(datetime.now()) ``` ```py from datetime import datetime print(datetime.today()) ``` ```py from datetime import datetime print(datetime.utcnow()) ```

[!NOTE]

Python doc states that date.now() is the preferred approach compare to date.today() and date.utcnow() (ref).

We can get the difference of times like this:

from datetime import datetime
birthdate = datetime(2005, 1, 1)
today = datetime.today()
print(today - birthdate)

[!CAUTION]

You cannot add two dates together, it will crash your app, for adding you need to use timedelta:

from datetime import date
date1 = date(2004, 12, 31)
date2 = date(2005, 1, 1)
print(date1 + date2)

timedelta

from datetime import date, timedelta
duration = timedelta(days=10)
opening_date = date(2025, 7, 20)
end_date = opening_date + duration
print(end_date)

Note: date object does not have a time component, meaning if we specify hour, it will be lost. E.g. timedelta(days=10, hours=1). But increasing it to 24 will make it a whole day, so it will change the returned value.

time

from datetime import time
print(time(12, 30))

[!NOTE]

You cannot subtract instances of times, i.e. the following code crashes:

from datetime import time
print(time(12, 10) - time(12, 30))
Traceback (most recent call last):
  File "/home/kasir/projects/python/main.py", line 2, in <module>
    print(time(12, 10) - time(12, 30))
          ~~~~~~~~~~~~~^~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

ISO 8601

isoformat date.fromisoformat
```py from datetime import datetime print(datetime(2023, 1, 1).isoformat()) ``` ```py from datetime import date print(date.fromisoformat("2023-01-01")) ```

YouTube/Aparat