13장 Calendars and Clocks
Table of contents
- Leap Year(윤년)
- The datetime Module
- Using the time Module
- Read and Write Dates and Times
- All the Conversions
- Alternative Modules
- Coming Up
- Things to Do
Python’s standard library has many date and time modules, including: datetime
, time
, calendar
, dateutil
, and others.
Leap Year(윤년)
윤년은 특정한 시간 주기다.
>>> import calendar
>>> calendar.isleap(1900)
False
>>> calendar.isleap(1996)
True
>>> calendar.isleap(1999)
False
>>> calendar.isleap(2000)
True
>>> calendar.isleap(2002)
False
>>> calendar.isleap(2004)
True
For the curious:
- A year has 365.242196 days (after one spin around the sun, the earth is about a quarter-turn on its axis from where it started).
- Add one day every four years. Now an average year has 365.242196 – 0.25 = 364.992196 days
- Subtract a day every 100 years. Now an average year has 364.992196 + 0.01 = 365.002196 days
- Add a day every 400 years. Now an average year has 365.002196 – 0.0025 = 364.999696 days
Close enough for now! We will not speak of leap seconds.
The datetime Module
The standard datetime module handles (which should not be a surprise) dates and times. It defines four main object classes, each with many methods:
date
: years, months, and daystime
: hours, minutes, seconds, and fractionsdatetime
: dates, timestimedelta
: date and/or time intervals
You can make a date object by specifying a year, month, and day. Those values are then available as attributes:
from datetime import date
halloween = date(2019, 10, 31)
print(halloween) # datetime.date(2019, 10, 31)
print(halloween.day) # 31
now = date.today()
print(now) # 오늘 날짜 출력
from datetime import *
delta = timedelta(days=1)
now = datetime.now()
tomorrow = now + delta
print('now : %s, tomorrow : %s'%(now,tomorrow))
print(now + 17*delta) # 17일 후
# 타임 다루기
from datetime import time
noon = time(12, 0, 0)
print(noon) # datetime.time(12, 0)
print(noon.hour) # 12
from datetime import datetime
some_day = datetime(2019, 1, 2, 3, 4, 5, 6) #마지막인수 - 마이크로초
print(some_day) # datetime.datetime(2019, 1, 2, 3, 4, 5, 6)
iso = some_day.isoformat() # datetime자료형 -> 인식 가능 하게
print(iso) # 2019-01-02T03:04:05.000006
now = datetime.now()
print(now) # 2022-12-30 22:09:49.004540
print(now.year) # 2022
d = some_day.date() # date부분만 추출
print(d) # 2019-01-02
s = some_day.time() # time부분만 추출
print(s) # 03:04:05.000006
con = datetime.combine(d,s) # date, time -> datetime으로
print(con) # 2019-01-02 03:04:05.000006
Using the time Module
유닉스 계열의 시간 개념 (다른 시스템과 교환 가능): 1970/1/1 자정 이후의 초를 사용한다 - epoch값
The time module’s time() function returns the current time as an epoch value:
>>> import time
>>> now = time.time()
>>> now
1554512132.778233
>>> time.ctime(now)
'Fri Apr 5 19:55:32 2019'
import time
now = time.time()
t = time.localtime() # 현시간 표준시
t1 = time.gmtime() # 현시간 UTC(절대시간)
print(now)
print(t)
print(t1)
'''
1674095102.1614609
time.struct_time(tm_year=2023, tm_mon=1, tm_mday=19, tm_hour=11, tm_min=25, tm_sec=2, tm_wday=3, tm_yday=19, tm_isdst=0)
time.struct_time(tm_year=2023, tm_mon=1, tm_mday=19, tm_hour=2, tm_min=25, tm_sec=2, tm_wday=3, tm_yday=19, tm_isdst=0)
'''
Table 13-1. struct_time values
Index | Name | Meaning | Values |
---|---|---|---|
0 | tm_year | Year | 0000 to 9999 |
1 | tm_mon | Month | 1 to 12 |
2 | tm_mday | Day of month | 1 to 31 |
3 | tm_hour | Hour | 0 to 23 |
4 | tm_min | Minute | 0 to 59 |
5 | tm_sec | Second | 0 to 61 |
6 | tm_wday | Day of week | 0 (Monday) to 6 (Sunday) |
7 | tm_yday | Day of year | 1 to 366 |
8 | tm_isdst | Daylight savings? | 0 = no, 1 = yes, -1 = unknown |
Read and Write Dates and Times
You can also convert dates and times to strings by using strftime()
. This is provided as a method in the datetime, date, and time objects, and as a function in the time module. strftime() uses format strings to specify the output, which you can see in Table 13-2.
Table 13-2. Output specifiers for strftime()
Format string | Date/time unit | Range |
---|---|---|
%Y | year | 1900 -… |
%m | month | 01 - 12 |
%B | month name | January, … |
%b | month abbrev | Jan, … |
%d | day of month | 01 - 31 |
%A | weekday name | Sunday, … |
a | weekday abbrev | Sun, … |
%H | hour (24 hr) | 00 - 23 |
%I | hour (12 hr) | 01 - 12 |
%p | AM/PM | AM, PM |
%M | minute | 00 - 59 |
%S | second | 00 - 59 |
- localtime -> 포멧된 time
import time
fmt = "It's %A, %B %d, %Y, local time %I:%M:%S%p"
t = time.localtime()
s = time.strftime(fmt, t)
print(s) # "It's Wednesday, March 13, 2019, local time 03:23:46PM"
- date객체 -> 포멧된 time
from datetime import date
some_day = date(2019, 7, 4)
fmt = "It's %A, %B %d, %Y, local time %I:%M:%S%p"
s = some_day.strftime(fmt)
print(s) # "It's Thursday, July 04, 2019, local time 12:00:00AM"
- time객체 -> 포멧된 time
from datetime import time
fmt = "It's %A, %B %d, %Y, local time %I:%M:%S%p"
some_time = time(10, 35)
s=some_time.strftime(fmt)
print(s) # "It's Monday, January 01, 1900, local time 10:35:00AM"
- 문자열 -> struct_time
import time fmt = "%Y-%m-%d" s = time.strptime("2019-01-29", fmt) print(s) # time.struct_time(tm_year=2019, tm_mon=1, tm_mday=29, tm_hour=0,tm_min=0, tm_sec=0, tm_wday=1, tm_yday=29, tm_isdst=-1)
Names are specific to your locale—internationalization settings for your operating system. If you need to print different month and day names, change your locale by using setlocale(); its first argument is locale.LC_TIME for dates and times, and the second is a string combining the language and country abbreviation. Let’s invite some
international friends to a Halloween party. We’ll print the month, day, and day of week in US English, French, German, Spanish, and Icelandic (Icelanders have real elves):
import locale
from datetime import date
halloween = date(2019, 10, 31)
for lang_country in ['en_us', 'fr_fr', 'de_de', 'es_es', 'is_is','ko-ko']:
s = locale.setlocale(locale.LC_TIME, lang_country)
print(s)
s1 = halloween.strftime('%A, %B %d')
print(s1.encode('utf-8', 'replace').decode())
'''
Thursday, October 31
jeudi, octobre 31
Donnerstag, Oktober 31
jueves, octubre 31
fimmtudagur, okt?ber 31
jeudi, octobre 31
de_de
Donnerstag, Oktober 31
es_es
jueves, octubre 31
is_is
fimmtudagur, október 31
ko-ko
목요일, 10월 31
'''
# 국가코드 확인 : dict형식
names = locale.locale_alias
print(names)
All the Conversions
Figure 13-1 (from the Python wiki) summarizes all the standard Python time inter‐
conversions.
Figure 13-1. Date and time conversions
Alternative Modules
arrow : Combines many date and time functions with a simple API
dateutil : Parses almost any date format and handles relative dates and times well
iso8601 : Fills in gaps in the standard library for the ISO8601 format
fleming : Many time zone functions
maya : Intuitive interface to dates, times, and intervals
dateinfer : Guesses the right format strings from date/time strings
Coming Up
Files and directories need love, too.
Things to Do
13.1 Write the current date as a string to the text file today.txt.
13.2 Read the text file today.txt into the string today_string.
13.3 Parse the date from today_string.
13.4 Create a date object of your day of birth.
13.5 What day of the week was your day of birth?
13.6 When will you be (or when were you) 10,000 days old?