lfalanga
11/18/2019 - 9:42 PM

Dates in Python

# Import datetime library
from datetime import datetime

# Example 1
now = datetime.now()
print now

# Example 2
now = datetime.now()
print now.year
print now.month
print now.day

# Example 3
now = datetime.now()
# date format: mm/dd/aaaa
print '%02d/%02d/%04d' % (now.month, now.day, now.year)
# hour format: hh:mm:ss
print '%02d:%02d:%02d' % (now.hour, now.minute, now.second)
# date and time format: mm/dd/aaaa hh:mm:ss
print '%02d/%02d/%04d %02d:%02d:%02d' % (now.month, now.day, now.year, now.hour, now.minute, now.second)

# Example 4
import datetime
import calendar

datetime.datetime.now()
print(datetime.datetime.utcnow()) # 2020-02-08 21:42:05.297830
print(datetime.datetime.now())  # 2020-02-08 18:42:05.298136
print(datetime.datetime.now().day)  # 8
print(datetime.datetime.now().month)  # 2
print(datetime.datetime.now().minute) # 42
print(datetime.datetime.now().second) # 5
print(datetime.datetime.now().microsecond) # 299232

# Example 5
print(datetime.datetime.today().strftime("%a %H:%M:%S %d/%m/%y %Z"))

# FORMATTING DATE OBJECTS (ABBREVIATIONS)
# %a - Day of the week name
# %A - Day of the week name (complete)
# %b - Month name
# %B - Month name (complete)
# %c - Actual time and date
# %d - Day of the month
# %H - Time (24hs format)
# %I - Time (12hs format)
# %j - Day of the year
# %m - Month number
# %M - Minutes
# %p - AM or PM
# %S - Seconds
# %U - Week of the year (Sunday as the first day of the week)
# %w - Day of the week
# %W - Week of the year (Monday as the first day of the week)
# %x - Actual date
# %X - Actual time
# %y - Year number (14)
# %Y - Year number (2014)
# %Z - Time zone

# Example 6: Time difference
actual = datetime.datetime.now()
anterior = datetime.datetime(1975, 9, 15, 0, 0, 0)
print(actual - anterior)

# Example 7: Five days ago
hoy = datetime.date.today()
hace5 = datetime.timedelta(days=5)
print(hoy)
print(hace5)
print(hoy - hace5)