Saturday, July 2, 2022

Python - Dates

import datetime

x = datetime.datetime.now()
# 2022-07-02 18:23:57.824673
print(x)

# The datetime module has many methods, here are some

# 2022
print(x.year)

# Saturday
print(x.strftime("%A"))

# Create a date object

x = datetime.datetime(2020, 5, 17)
# 2020-05-17 00:00:00
print(x)

# Format date objects into readable strings via strftime()
# Good listing at w3schools:
# https://www.w3schools.com/python/python_datetime.asp

x = datetime.datetime(2018, 6, 1)

# %B = Month name
# June
print(x.strftime("%B"))

# %Y = year
# 2018
print(x.strftime("%Y"))

# %m = month as a two digit number
# 06
print(x.strftime("%m"))

# %d = day as a two digit number
# 01
print(x.strftime("%d"))

# There's probably a better way to do it than this
myFormattedDate = x.strftime("%Y") + "-" \
    + x.strftime("%m") + "-" \
    + x.strftime("%d")

# 2018-06-01
print(myFormattedDate)

# This works the same way
myFormattedDate = x.strftime('%Y-%m-%d')
print(myFormattedDate)

# Today's date
# 2022-07-02 18:42:02.671457
print(datetime.datetime.today())

# 2022-07-02
print(datetime.datetime.today().strftime('%Y-%m-%d'))