10.4 달력과 시간

import calendar
calendar.isleap(2000)

True

10.4.1 datetime 모듈

  • date: 년, 월, 일
  • time: 시, 분, 초, 마이크로초
  • datetime 날짜와 시간
  • timedelta 날짜 와/또는 시간 간격``
    from datetime import date
    halloween = date(2015, 10, 31)
    halloween
    

    datetime.date(2015, 10, 31)

    halloween.day
    

    31

    halloween.month
    

    10

    halloween.year
    

    2015

    halloween.isoformat()
    

    ‘2015-10-31’

  • iso는 국제 표준화 기구에서 재정한 날짜와 시간 표현에 대한 국제표준규걱인 ISO8601을 참고한다.
    from datetime import date
    now = date.today()
    now
    

    datetime.date(2018, 3, 6)

    from datetime import timedelta
    one_day = timedelta(days=1)
    tomorrow = now + one_day
    tomorrow
    

    datetime.date(2018, 3, 7)

    now + 17*one_day
    

    datetime.date(2018, 3, 23)

    yesterday = now - one_day
    yesterday
    

    datetime.date(2018, 3, 5)

  • 날짜의 범위는 date.min(year=1, month=1, day=1) 부터 date.max(year=9999, month=12, day=31)까지다.
    from datetime import time
    noon = time(12, 0, 0)
    noon
    

    datetime.time(12, 0)

    noon.hour
    

    12

    noon.minute
    

    0

    noon.second
    

    0

    noon.microsecond
    

    0

    from datetime import datetime
    some_day = datetime(2015, 1, 2, 3, 4, 5, 6)
    
    some_day
    

    datetime.datetime(2015, 1, 2, 3, 4, 5, 6)

    some_day.isoformat()
    

    ‘2015-01-02T03:04:05.000006’

  • datetime 객체에서 now() 메서드로 현재 날짜와 시간을 얻을수 있다.
    from datetime import datetime
    now = datetime.now()
    
    now
    

    datetime.datetime(2018, 3, 6, 10, 13, 9, 87686)

    now.year
    

    2018

    now.month
    

    3

    now.day
    

    6

    now.hour
    

    10

    now.minute
    

    13

    now.second
    

    9

    now.microsecond
    

    87686

  • combine으로 date객체와 time객체를 datetime객체로 병합할 수 있다.
    from datetime import datetime, time, date
    noon = time(12)
    this_day = date.today()
    noon_today = datetime.combine(this_day, noon)
    noon_today
    

    datetime.datetime(2018, 3, 6, 12, 0)

  • defatime 객체에서 date()와 time() 메서드를 사용하여 날짜와 시간을 얻을 수 있다.
    noon_today.date()
    

    datetime.date(2018, 3, 6)

    noon_today.time()
    

    datetime.time(12, 0)

    10.4.2 time 모듈

  • 유닉스 시간은 1970년 1월 1일 자정 이후 시간의 초를 사용한다.
  • 이값을 에포치(epoch)라고 부르며 에포치는 시스테 ㅁ간에 날짜와 시간을 교환하는 아주 간단한방식이다.
  • time 모듈의 time() 함수는 현재시간을 에포치값으로 반환한다.
    import time
    now = time.time()
    now
    

    1520299451.8630648

    time.ctime(now)
    

    ‘Tue Mar 6 10:24:11 2018’

  • localtime() 메서드는 시간을 시스템 표준 시간대로
  • gmtime() 메서드는 시간을 UTC로 제공한다.
    time.localtime(now)
    

    time.struct_time(tm_year=2018, tm_mon=3, tm_mday=6, tm_hour=10, tm_min=24, tm_sec=11, tm_wday=1, tm_yday=65, tm_isdst=0)

    time.gmtime(now)
    

    time.struct_time(tm_year=2018, tm_mon=3, tm_mday=6, tm_hour=1, tm_min=24, tm_sec=11, tm_wday=1, tm_yday=65, tm_isdst=0)

  • 한국의 현재시간 10:24는 그 전날의 UTC(그리니치 시간, 줄루 시간)로 1:24 다
  • 인자를 생략하면 현재 시간이다.
  • mktime() 메서드는 struct_time 객체를 에포치 초 로 변환한다.
    tm = time.localtime(now)
    time.mktime(tm)
    

    1520299451.0

  • 이 값은 조금전에 본 now()의 에초피 값과 정확하게 일치 하지 않는다. struct_time 객체는 시간을 초 까지만 유지하기 때문.
  • UTC를 사용하라.
  • 일광절약시간은 사용하지 마라.
  • 시간에 대해서는 UTC, 문자열에 대해서는 UTF-8을 가까이 하라

    10.4.3 날짜와 시간 읽고 쓰기

    import time
    now = time.time()
    print(now)
    print(time.ctime(now))
    print(time.mktime(time.localtime(now)))
    

    1520299927.684161 Tue Mar 6 10:32:07 2018 1520299927.0

  • strftime() 은 문자열의 출력 포맷을 지정할 수 있다.
    import time
    fmt = "It's %A, %B, %d, %Y, local time %I:%M:%Sp"
    t = time.localtime()
    t
    

    time.struct_time(tm_year=2018, tm_mon=3, tm_mday=6, tm_hour=10, tm_min=32, tm_sec=55, tm_wday=1, tm_yday=65, tm_isdst=0)

    time.strftime(fmt, t)
    

    “It’s Tuesday, March, 06, 2018, local time 10:32:55p”

    from datetime import date
    some_day = date(2015, 12, 12)
    fmt = "It's %A, %B, %d, %Y, local time %I:%M:%Sp"
    some_day.strftime(fmt)
    

    “It’s Saturday, December, 12, 2015, local time 12:00:00p”

    from datetime import time
    some_time = time(10, 35)
    some_time.strftime(fmt)
    

    “It’s Monday, January, 01, 1900, local time 10:35:00p”

  • 문자열을 날짜나 시간으로 변환하기 위해 같은 포맷 문자열로 strptime()을 사용한다.
  • 정규 표현식 패턴 매칭은 없다.
  • 문자열의 비형식 부분(% 제외)이 정확히 일치해야 한다.
    import time
    fmt = "%Y-%m-%d"
    time.strptime("2015 06 02", fmt)
    
ValueError Traceback (most recent call last)
<ipython-input-47-c984d95f7252> in <module>()
1 import time
2 fmt = "%Y-%m-%d"
----> 3 time.strptime("2015 06 02", fmt)

~/.pyenv/versions/3.6.4/lib/python3.6/_strptime.py in _strptime_time(data_string, format)
557     """Return a time struct based on the input string and the
558     format string."""
--> 559     tt = _strptime(data_string, format)[0]
560     return time.struct_time(tt[:time._STRUCT_TM_ITEMS])
561
~/.pyenv/versions/3.6.4/lib/python3.6/_strptime.py in _strptime(data_string, format)
360     if not found:
361         raise ValueError("time data %r does not match format %r" %
--> 362                          (data_string, format))
363     if len(data_string) != found.end():
364         raise ValueError("unconverted data remains: %s" %
ValueError: time data '2015 06 02' does not match format '%Y-%m-%d'
time.strptime("2015-06-02", fmt)

time.struct_time(tm_year=2015, tm_mon=6, tm_mday=2, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=153, tm_isdst=-1)

time.strptime("2015-13-29", fmt)
ValueError Traceback (most recent call last)
<ipython-input-49-e947ddabad6b> in <module>()
----> 1 time.strptime("2015-13-29", fmt)

~/.pyenv/versions/3.6.4/lib/python3.6/_strptime.py in _strptime_time(data_string, format)
557     """Return a time struct based on the input string and the
558     format string."""
--> 559     tt = _strptime(data_string, format)[0]
560     return time.struct_time(tt[:time._STRUCT_TM_ITEMS])
561
~/.pyenv/versions/3.6.4/lib/python3.6/_strptime.py in _strptime(data_string, format)
360     if not found:
361         raise ValueError("time data %r does not match format %r" %
--> 362                          (data_string, format))
363     if len(data_string) != found.end():
364         raise ValueError("unconverted data remains: %s" %
ValueError: time data '2015-13-29' does not match format '%Y-%m-%d'
  • 이름은 locale에 따라 다르다.
  • 다른 월, 일의 이름을 출력하며녀 setlocale()을 사용하여 로케일을 바꿔야 한다.
  • setlocale()의 첫번째 인자는 날짜와 시간을 위한 locale.LC_TIME이고, 두 번째는 언어와 국가 약어가 결합된 문자열이다.
    import locale
    from datetime import date
    halloween = date(2015, 10, 31)
    for lang_country in ['ko_kr', 'en_us', 'fr_fr', 'de_de', 'es_es', 'is_is']:
    locale.setlocale(locale.LC_TIME, lang_country)
    halloween.strftime('%A, %B, %d')
    
Error Traceback (most recent call last)
<ipython-input-59-cd0e7e432ab6> in <module>()
3 halloween = date(2015, 10, 31)
4 for lang_country in ['en_us']:
----> 5     locale.setlocale(locale.LC_TIME, lang_country)
6     halloween.strftime('%A, %B, %d')
~/.pyenv/versions/3.6.4/lib/python3.6/locale.py in setlocale(category, locale)
596         # convert to string
597         locale = normalize(_build_localename(locale))
--> 598     return _setlocale(category, locale)
599
600 def resetlocale(category=LC_ALL):
Error: unsupported locale setting
import locale
names = locale.locale_alias.keys()
names

dict_keys([‘a3’, ‘a3_az’, ‘a3_az.koic’, ‘aa_dj’, ‘aa_er’, ‘aa_et’, ‘af’, ‘af_za’, ‘am’, ‘am_et’, ‘american’, ‘an_es’, ‘ar’, ‘ar_aa’, ‘ar_ae’, ‘ar_bh’, ‘ar_dz’, ‘ar_eg’, ‘ar_in’, ‘ar_iq’, ‘ar_jo’, ‘ar_kw’, ‘ar_lb’, ‘ar_ly’, ‘ar_ma’, ‘ar_om’, ‘ar_qa’, ‘ar_sa’, ‘ar_sd’, ‘ar_sy’, ‘ar_tn’, ‘ar_ye’, ‘arabic’, ‘as’, ‘as_in’, ‘ast_es’, ‘ayc_pe’, ‘az’, ‘az_az’, ‘az_az.iso88599e’, ‘be’, ‘be@latin’, ‘be_bg.utf8’, ‘be_by’, ‘be_by@latin’, ‘bem_zm’, ‘ber_dz’, ‘ber_ma’, ‘bg’, ‘bg_bg’, ‘bho_in’, ‘bn_bd’, ‘bn_in’, ‘bo_cn’, ‘bo_in’, ‘bokmal’, ‘bokmål’, ‘br’, ‘br_fr’, ‘brx_in’, ‘bs’, ‘bs_ba’, ‘bulgarian’, ‘byn_er’, ‘c’, ‘c-french’, ‘c.ascii’, ‘c.en’, ‘c.iso88591’, ‘c.utf8’, ‘c_c’, ‘c_c.c’, ‘ca’, ‘ca_ad’, ‘ca_es’, ‘ca_es@valencia’, ‘ca_fr’, ‘ca_it’, ‘catalan’, ‘cextend’, ‘chinese-s’, ‘chinese-t’, ‘crh_ua’, ‘croatian’, ‘cs’, ‘cs_cs’, ‘cs_cz’, ‘csb_pl’, ‘cv_ru’, ‘cy’, ‘cy_gb’, ‘cz’, ‘cz_cz’, ‘czech’, ‘da’, ‘da_dk’, ‘danish’, ‘dansk’, ‘de’, ‘de_at’, ‘de_be’, ‘de_ch’, ‘de_de’, ‘de_li.utf8’, ‘de_lu’, ‘deutsch’, ‘doi_in’, ‘dutch’, ‘dutch.iso88591’, ‘dv_mv’, ‘dz_bt’, ‘ee’, ‘ee_ee’, ‘eesti’, ‘el’, ‘el_cy’, ‘el_gr’, ‘el_gr@euro’, ‘en’, ‘en_ag’, ‘en_au’, ‘en_be’, ‘en_bw’, ‘en_ca’, ‘en_dk’, ‘en_dl.utf8’, ‘en_gb’, ‘en_hk’, ‘en_ie’, ‘en_in’, ‘en_ng’, ‘en_nz’, ‘en_ph’, ‘en_sg’, ‘en_uk’, ‘en_us’, ‘en_us@euro@euro’, ‘en_za’, ‘en_zm’, ‘en_zw’, ‘en_zw.utf8’, ‘eng_gb’, ‘english’, ‘english_uk’, ‘english_united-states’, ‘english_united-states.437’, ‘english_us’, ‘eo’, ‘eo.utf8’, ‘eo_eo’, ‘eo_us.utf8’, ‘eo_xx’, ‘es’, ‘es_ar’, ‘es_bo’, ‘es_cl’, ‘es_co’, ‘es_cr’, ‘es_cu’, ‘es_do’, ‘es_ec’, ‘es_es’, ‘es_gt’, ‘es_hn’, ‘es_mx’, ‘es_ni’, ‘es_pa’, ‘es_pe’, ‘es_pr’, ‘es_py’, ‘es_sv’, ‘es_us’, ‘es_uy’, ‘es_ve’, ‘estonian’, ‘et’, ‘et_ee’, ‘eu’, ‘eu_es’, ‘eu_fr’, ‘fa’, ‘fa_ir’, ‘fa_ir.isiri3342’, ‘ff_sn’, ‘fi’, ‘fi_fi’, ‘fil_ph’, ‘finnish’, ‘fo’, ‘fo_fo’, ‘fr’, ‘fr_be’, ‘fr_ca’, ‘fr_ch’, ‘fr_fr’, ‘fr_lu’, ‘français’, ‘fre_fr’, ‘french’, ‘french.iso88591’, ‘french_france’, ‘fur_it’, ‘fy_de’, ‘fy_nl’, ‘ga’, ‘ga_ie’, ‘galego’, ‘galician’, ‘gd’, ‘gd_gb’, ‘ger_de’, ‘german’, ‘german.iso88591’, ‘german_germany’, ‘gez_er’, ‘gez_et’, ‘gl’, ‘gl_es’, ‘greek’, ‘gu_in’, ‘gv’, ‘gv_gb’, ‘ha_ng’, ‘he’, ‘he_il’, ‘hebrew’, ‘hi’, ‘hi_in’, ‘hi_in.isciidev’, ‘hne’, ‘hne_in’, ‘hr’, ‘hr_hr’, ‘hrvatski’, ‘hsb_de’, ‘ht_ht’, ‘hu’, ‘hu_hu’, ‘hungarian’, ‘hy_am’, ‘hy_am.armscii8’, ‘ia’, ‘ia_fr’, ‘icelandic’, ‘id’, ‘id_id’, ‘ig_ng’, ‘ik_ca’, ‘in’, ‘in_id’, ‘is’, ‘is_is’, ‘iso-8859-1’, ‘iso-8859-15’, ‘iso8859-1’, ‘iso8859-15’, ‘iso_8859_1’, ‘iso_8859_15’, ‘it’, ‘it_ch’, ‘it_it’, ‘italian’, ‘iu’, ‘iu_ca’, ‘iu_ca.nunacom8’, ‘iw’, ‘iw_il’, ‘iw_il.utf8’, ‘ja’, ‘ja_jp’, ‘ja_jp.euc’, ‘ja_jp.mscode’, ‘ja_jp.pck’, ‘japan’, ‘japanese’, ‘japanese-euc’, ‘japanese.euc’, ‘jp_jp’, ‘ka’, ‘ka_ge’, ‘ka_ge.georgianacademy’, ‘ka_ge.georgianps’, ‘ka_ge.georgianrs’, ‘kk_kz’, ‘kl’, ‘kl_gl’, ‘km_kh’, ‘kn’, ‘kn_in’, ‘ko’, ‘ko_kr’, ‘ko_kr.euc’, ‘kok_in’, ‘korean’, ‘korean.euc’, ‘ks’, ‘ks_in’, ‘ks_in@devanagari.utf8’, ‘ku_tr’, ‘kw’, ‘kw_gb’, ‘ky’, ‘ky_kg’, ‘lb_lu’, ‘lg_ug’, ‘li_be’, ‘li_nl’, ‘lij_it’, ‘lithuanian’, ‘lo’, ‘lo_la’, ‘lo_la.cp1133’, ‘lo_la.ibmcp1133’, ‘lo_la.mulelao1’, ‘lt’, ‘lt_lt’, ‘lv’, ‘lv_lv’, ‘mag_in’, ‘mai’, ‘mai_in’, ‘mg_mg’, ‘mhr_ru’, ‘mi’, ‘mi_nz’, ‘mk’, ‘mk_mk’, ‘ml’, ‘ml_in’, ‘mn_mn’, ‘mni_in’, ‘mr’, ‘mr_in’, ‘ms’, ‘ms_my’, ‘mt’, ‘mt_mt’, ‘my_mm’, ‘nan_tw@latin’, ‘nb’, ‘nb_no’, ‘nds_de’, ‘nds_nl’, ‘ne_np’, ‘nhn_mx’, ‘niu_nu’, ‘niu_nz’, ‘nl’, ‘nl_aw’, ‘nl_be’, ‘nl_nl’, ‘nn’, ‘nn_no’, ‘no’, ‘no@nynorsk’, ‘no_no’, ‘no_no.iso88591@bokmal’, ‘no_no.iso88591@nynorsk’, ‘norwegian’, ‘nr’, ‘nr_za’, ‘nso’, ‘nso_za’, ‘ny’, ‘ny_no’, ‘nynorsk’, ‘oc’, ‘oc_fr’, ‘om_et’, ‘om_ke’, ‘or’, ‘or_in’, ‘os_ru’, ‘pa’, ‘pa_in’, ‘pa_pk’, ‘pap_an’, ‘pd’, ‘pd_de’, ‘pd_us’, ‘ph’, ‘ph_ph’, ‘pl’, ‘pl_pl’, ‘polish’, ‘portuguese’, ‘portuguese_brazil’, ‘posix’, ‘posix-utf2’, ‘pp’, ‘pp_an’, ‘ps_af’, ‘pt’, ‘pt_br’, ‘pt_pt’, ‘ro’, ‘ro_ro’, ‘romanian’, ‘ru’, ‘ru_ru’, ‘ru_ua’, ‘rumanian’, ‘russian’, ‘rw’, ‘rw_rw’, ‘sa_in’, ‘sat_in’, ‘sc_it’, ‘sd’, ‘sd_in’, ‘sd_in@devanagari.utf8’, ‘sd_pk’, ‘se_no’, ‘serbocroatian’, ‘sh’, ‘sh_ba.iso88592@bosnia’, ‘sh_hr’, ‘sh_hr.iso88592’, ‘sh_sp’, ‘sh_yu’, ‘shs_ca’, ‘si’, ‘si_lk’, ‘sid_et’, ‘sinhala’, ‘sk’, ‘sk_sk’, ‘sl’, ‘sl_cs’, ‘sl_si’, ‘slovak’, ‘slovene’, ‘slovenian’, ‘so_dj’, ‘so_et’, ‘so_ke’, ‘so_so’, ‘sp’, ‘sp_yu’, ‘spanish’, ‘spanish_spain’, ‘sq’, ‘sq_al’, ‘sq_mk’, ‘sr’, ‘sr@cyrillic’, ‘sr@latn’, ‘sr_cs’, ‘sr_cs.iso88592@latn’, ‘sr_cs@latn’, ‘sr_me’, ‘sr_rs’, ‘sr_rs@latn’, ‘sr_sp’, ‘sr_yu’, ‘sr_yu.cp1251@cyrillic’, ‘sr_yu.iso88592’, ‘sr_yu.iso88595’, ‘sr_yu.iso88595@cyrillic’, ‘sr_yu.microsoftcp1251@cyrillic’, ‘sr_yu.utf8’, ‘sr_yu.utf8@cyrillic’, ‘sr_yu@cyrillic’, ‘ss’, ‘ss_za’, ‘st’, ‘st_za’, ‘sv’, ‘sv_fi’, ‘sv_se’, ‘sw_ke’, ‘sw_tz’, ‘swedish’, ‘szl_pl’, ‘ta’, ‘ta_in’, ‘ta_in.tscii’, ‘ta_in.tscii0’, ‘ta_lk’, ‘te’, ‘te_in’, ‘tg’, ‘tg_tj’, ‘th’, ‘th_th’, ‘th_th.tactis’, ‘th_th.tis620’, ‘thai’, ‘ti_er’, ‘ti_et’, ‘tig_er’, ‘tk_tm’, ‘tl’, ‘tl_ph’, ‘tn’, ‘tn_za’, ‘tr’, ‘tr_cy’, ‘tr_tr’, ‘ts’, ‘ts_za’, ‘tt’, ‘tt_ru’, ‘tt_ru.tatarcyr’, ‘tt_ru@iqtelif’, ‘turkish’, ‘ug_cn’, ‘uk’, ‘uk_ua’, ‘univ’, ‘universal’, ‘universal.utf8@ucs4’, ‘unm_us’, ‘ur’, ‘ur_in’, ‘ur_pk’, ‘uz’, ‘uz_uz’, ‘uz_uz@cyrillic’, ‘ve’, ‘ve_za’, ‘vi’, ‘vi_vn’, ‘vi_vn.tcvn’, ‘vi_vn.tcvn5712’, ‘vi_vn.viscii’, ‘vi_vn.viscii111’, ‘wa’, ‘wa_be’, ‘wae_ch’, ‘wal_et’, ‘wo_sn’, ‘xh’, ‘xh_za’, ‘yi’, ‘yi_us’, ‘yo_ng’, ‘yue_hk’, ‘zh’, ‘zh_cn’, ‘zh_cn.big5’, ‘zh_cn.euc’, ‘zh_hk’, ‘zh_hk.big5hk’, ‘zh_sg’, ‘zh_sg.gbk’, ‘zh_tw’, ‘zh_tw.euc’, ‘zh_tw.euctw’, ‘zu’, ‘zu_za’])

good_names = [name for name in names if len(name) == 5 and name[2] == '_']
good_names[:5]

[‘a3_az’, ‘aa_dj’, ‘aa_er’, ‘aa_et’, ‘af_za’]

de = [name for name in good_names if name.startswith('de')]
de

[‘de_at’, ‘de_be’, ‘de_ch’, ‘de_de’, ‘de_lu’]

10.4.4 대체 모듈

Comments