Search notes:

Python standard library: datetime

The Python module datetime provides date and time calculations.

strptime

import datetime

date_str = '1970-08-28 22:23:24'

dt = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')

print (dt.strftime('%H:%M:%S %d.%m.%Y'))
Github repository about-python, path: /standard-library/datetime/datetime/strptime.py
Compare with the R function strptime and the Perl module DateTime::Format::Strptime.

datetime.toordinal

datetime.toordinal(…) returns the number of days since December 31, 1 BC at 00:00 in the proleptic Gregorian date:
import datetime

print(datetime.datetime.strptime('0001-01-01', '%Y-%m-%d').toordinal()) #      1

print(datetime.datetime.strptime('1582-10-04', '%Y-%m-%d').toordinal()) # 577725
print(datetime.datetime.strptime('1582-10-05', '%Y-%m-%d').toordinal()) # 577726 - inexisting date
print(datetime.datetime.strptime('1582-10-06', '%Y-%m-%d').toordinal()) # 577727 - inexisting date

print(datetime.datetime.strptime('1582-10-15', '%Y-%m-%d').toordinal()) # 577736 - 1st gregorian day
Github repository about-python, path: /standard-library/datetime/datetime/toordinal.py

datetime.date

import datetime;


birthday_ = datetime.date(2014, 8, 28)
print ("Birthday: " + birthday_.strftime("%Y-%m-%d"))


# 

today_     = datetime.date.today()
in_a_week_ = today_ + datetime.timedelta(days = 7)

print ("The date in a week will be " + in_a_week_.strftime("%Y-%m-%d"))
Github repository about-python, path: /standard-library/datetime/date/script.py

datetime.timedelta

import datetime;

today_    = datetime.date.today()
tomorrow_ = today_ + datetime.timedelta(days = 1)

print ("The date in a week will be " + tomorrow_.strftime("%Y-%m-%d"))
Github repository about-python, path: /standard-library/datetime/timedelta/script.py

Calculating the Julian Day Number

The following snippet can be used to calculate the Julian Day:
import datetime
import sqlite3

print ( datetime.date(2025,10,27).toordinal()+1721424.5 )

#
#   Verify with with sqlite3 julianday function:
#
print (sqlite3.connect(':memory:').cursor().execute("select julianday('2025-10-27')").fetchone()[0])

See also

The standard library dateutil provides extensions to datetime.

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1788540753, '216.73.217.21', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Python/standard-library/datetime/index(112): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78