Python - Date and Time
-1. Date and Time Example
import calendar
from datetime import date
from datetime import datetime
from datetime import timedelta
if __name__ == '__main__':
# date:
today = date.today()
print("Today is ", today)
print(today.day, today.month, today.year)
print(today.weekday())
days = ["mon", 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
print(days[today.weekday()])
# datetime:
today = datetime.now()
print("Today is ", today)
t = datetime.time(datetime.now())
print(t)
# datetime format:
now = datetime.now()
print((now.strftime("%Y")))
print((now.strftime("%a, %d %B, %y")))
print(now.strftime("Locale date and time: %c"))
print(now.strftime("Locale date : %x"))
print(now.strftime("Locale time: %X"))
# time format:
print(now.strftime("%I:%M:%S %p"))
print(now.strftime("%H:%M"))
# time delta时间间隔
print(timedelta(days=365, hours=5, minutes=1))
now = datetime.now()
print("Today is ", str(now))
print("one year from now: " + str(now + timedelta(days=365)))
print(str(now + timedelta(days=2, weeks=3)))
t = datetime.now() - timedelta(weeks=1)
s = t.strftime("%A %B %d, %Y")
print(s)
today = date.today()
afd = date(today.year, 4, 1)
print(str(today))
print(str(afd))
if afd < today:
print("04/01 has gone %d" % (today - afd).days)
afd = afd.replace(year=today.year + 1)
print(afd)
time_to_aft = afd - today
print(time_to_aft)
# calendar
c = calendar.TextCalendar(calendar.SUNDAY)
st = c.formatmonth(2017, 1, 0, 0)
print(st)
hc = calendar.HTMLCalendar(calendar.MONDAY)
st = hc.formatmonth(2017, 1)
print(st)
for i in c.itermonthdays(2017, 1):
print(i)
for name in calendar.month_name:
print(name)
for day in calendar.day_name:
print(day)
# 1st Friday in each month
for m in range(1, 13):
cal = calendar.monthcalendar(2019, m)
weekone = cal[0]
weektwo = cal[1]
if weekone[calendar.FRIDAY] != 0:
meetday = weekone[calendar.FRIDAY]
else:
meetday = weektwo[calendar.FRIDAY]
print("%10s %2d" % (calendar.month_name[m], meetday))