Python 날짜/시간 모듈

Python에서 날짜와 시간은 자체 데이터 유형이 아니라 이름이 지정된 모듈입니다. 날짜 시간 Python에서는 날짜와 시간 작업을 위해 가져올 수 있습니다. Python 날짜/시간 모듈 Python에 내장되어 있으므로 외부에 설치할 필요가 없습니다.

이 기사에서는 방법을 살펴보겠습니다. Python의 날짜/시간 작동하며 Python에서 DateTime 모듈의 주요 클래스는 무엇입니까?

내용의 테이블

Python DateTime 모듈

Python 날짜/시간 모듈은 날짜와 시간을 다루는 클래스를 제공합니다. 이러한 클래스는 날짜, 시간 및 시간 간격을 처리하는 여러 함수를 제공합니다. Date 및 DateTime은 Python의 개체이므로 이를 조작하면 문자열이나 타임스탬프가 아닌 개체를 조작하게 됩니다.

DateTime 모듈은 6개의 주요 클래스로 분류됩니다.

  • 날짜 – 현재의 그레고리력이 항상 유효했고 앞으로도 유효할 것이라고 가정하는 이상적인 순진한 날짜입니다. 해당 속성은 연도, 월, 일입니다. 당신은 참조 할 수 있습니다 - Python DateTime - 날짜 클래스
  • 시간 – 매일이 정확히 24*60*60초라고 가정하고 특정 날짜와 무관한 이상적인 시간입니다. 해당 속성은 시, 분, 초, 마이크로초 및 tzinfo입니다. 당신은 참조 할 수 있습니다 – Python DateTime - 시간 클래스
  • 날짜 시간 – 연도, 월, 일, 시, 분, 초, 마이크로초, tzinfo 속성과 함께 날짜 및 시간의 조합입니다. 당신은 참조 할 수 있습니다 – Python DateTime – DateTime 클래스
  • 시간 델타 – 두 날짜, 시간 또는 날짜/시간 인스턴스 간의 차이를 마이크로초 단위로 표현하는 기간입니다. 당신은 참조 할 수 있습니다 - Python DateTime – Timedelta 클래스
  • tzinfo – 시간대 정보 객체를 제공합니다. 당신은 참조 할 수 있습니다 – 파이썬 – datetime.tzinfo()
  • 시간대 – UTC로부터의 고정 오프셋으로 tzinfo 추상 기본 클래스를 구현하는 클래스(버전 3.2의 새로운 기능). 당신은 참조 할 수 있습니다 – Python에서 시간대 처리

Python 날짜 클래스

날짜 클래스는 Python에서 날짜 객체를 인스턴스화하는 데 사용됩니다. 이 클래스의 객체가 인스턴스화되면 다음 형식으로 날짜를 나타냅니다. YYYY-MM-DD . 이 클래스의 생성자에는 연도, 월, 날짜 세 개의 필수 인수가 필요합니다.

Python 날짜 클래스 구문

class datetime.date(year, month, day) 

인수는 다음 범위에 있어야 합니다.

  • MINYEAR <= 연도 <= MAXYEAR
  • 1 <= 월 <= 12
  • 1 <= 일 <= 해당 월 및 연도의 일 수

메모 – 인수가 정수가 아니면 TypeError가 발생하고 범위를 벗어나면 ValueError가 발생합니다.

Python에서 데이터를 나타내는 날짜 객체

생성자를 초기화하고 연도, 월, 날짜 형식으로 인수를 전달합니다.

파이썬3




# Python program to> # demonstrate date class> # import the date class> from> datetime> import> date> my_date> => date(> 1996> ,> 12> ,> 11> )> print> (> 'Date passed as argument is'> , my_date)> # Uncommenting my_date = date(1996, 12, 39)> # will raise an ValueError as it is> # outside range> # uncommenting my_date = date('1996', 12, 11)> # will raise a TypeError as a string is> # passed instead of integer>

산출:

Date passed as argument is 1996-12-11 
Traceback (most recent call last):  File '/home/ccabfb570d9bd1dcd11dc4fe55fd6ba2.py', line 14, in   my_date = date(1996, 12, 39) ValueError: day is out of range for month  Traceback (most recent call last):  File '/home/53b974e10651f1853eee3c004b48c481.py', line 18, in   my_date = date('1996', 12, 11) TypeError: an integer is required (got type str) 

현재 날짜 가져오기

현재 지역 날짜를 반환하려면 날짜 클래스의 today() 함수를 사용합니다. today() 함수에는 여러 속성(연도, 월, 일)이 있습니다. 개별적으로 인쇄할 수 있습니다.

파이썬3




# Python program to> # print current date> from> datetime> import> date> # calling the today> # function of date class> today> => date.today()> print> (> 'Today's date is'> , today)>

산출

Today's date is 2021-08-19 

오늘의 연도, 월, 날짜 가져오기

날짜 클래스의 연도, 월, 날짜 속성을 사용하여 날짜 객체에서 연도, 월, 날짜 속성을 가져올 수 있습니다.

파이썬3




from> datetime> import> date> # date object of today's date> today> => date.today()> print> (> 'Current year:'> , today.year)> print> (> 'Current month:'> , today.month)> print> (> 'Current day:'> , today.day)>

산출

Current year: 2021 Current month: 8 Current day: 19 

타임스탬프에서 날짜 가져오기

fromtimestamp() 메소드를 사용하여 타임스탬프 y=에서 날짜 객체를 생성할 수 있습니다. 타임스탬프는 1970년 1월 1일 UTC부터 특정 날짜까지의 초 수입니다.

파이썬3




from> datetime> import> datetime> # Getting Datetime from timestamp> date_time> => datetime.fromtimestamp(> 1887639468> )> print> (> 'Datetime from timestamp:'> , date_time)>

산출

Datetime from timestamp: 2029-10-25 16:17:48 

날짜를 문자열로 변환

isoformat() 및 strftime() 두 함수를 사용하여 날짜 객체를 문자열 표현으로 변환할 수 있습니다.

파이썬3




from> datetime> import> date> > # calling the today> # function of date class> today> => date.today()> > # Converting the date to the string> Str> => date.isoformat(today)> print> (> 'String Representation'> ,> Str> )> print> (> type> (> Str> ))>

산출

String Representation 2021-08-19 

날짜 클래스 메서드 목록

기능 이름

설명

c시간() 날짜를 나타내는 문자열을 반환합니다.
fromisocalendar() ISO 달력에 해당하는 날짜를 반환합니다.
fromisoformat() 날짜의 문자열 표현에서 날짜 객체를 반환합니다.
서수() 1년 1월 1일이 서수 1인 역산 그레고리력 서수에서 날짜 객체를 반환합니다.
타임스탬프() POSIX 타임스탬프에서 날짜 객체를 반환합니다.
아이소캘린더() 튜플 연도, 주, 요일을 반환합니다.
아이소포맷() 날짜의 문자열 표현을 반환합니다.
isoweekday() 월요일이 1이고 일요일이 7인 정수로 요일을 반환합니다.
바꾸다() 주어진 매개변수로 날짜 객체의 값을 변경합니다.
strftime() 주어진 형식으로 날짜의 문자열 표현을 반환합니다.
타임튜플() time.struct_time 유형의 객체를 반환합니다.
오늘() 현재 현지 날짜를 반환합니다.
토서수() 1년 1월 1일이 서수 1인 날짜의 역산 그레고리력 서수를 반환합니다.
주일() 월요일이 0이고 일요일이 6인 경우 요일을 정수로 반환합니다.

Python 시간 클래스

time 클래스는 날짜와 관계없이 현지 시간을 나타내는 시간 객체를 생성합니다.

생성자 구문:

클래스 datetime.time(시간=0, 분=0, 초=0, 마이크로초=0, tzinfo=없음, *, 접기=0)

모든 인수는 선택 사항입니다. tzinfo는 None일 수 있습니다. 그렇지 않으면 모든 속성은 다음 범위의 정수여야 합니다.

  • 0 <= 시간 < 24
  • 0 <= 분 < 60
  • 0 <= 초 < 60
  • 0 <= 마이크로초 < 1000000
  • [0, 1]로 접기

예제 1: Python에서 시간을 나타내는 시간 객체

파이썬3




# Python program to> # demonstrate time class> from> datetime> import> time> # calling the constructor> my_time> => time(> 13> ,> 24> ,> 56> )> print> (> 'Entered time'> , my_time)> # calling constructor with 1> # argument> my_time> => time(minute> => 12> )> print> (> ' Time with one argument'> , my_time)> # Calling constructor with> # 0 argument> my_time> => time()> print> (> ' Time without argument'> , my_time)> # Uncommenting time(hour = 26)> # will rase an ValueError as> # it is out of range> # uncommenting time(hour ='23')> # will raise TypeError as> # string is passed instead of int>

산출:

Entered time 13:24:56  Time with one argument 00:12:00  Time without argument 00:00:00 
Traceback (most recent call last):  File '/home/95ff83138a1b3e67731e57ec6dddef25.py', line 21, in   print(time(hour=26)) ValueError: hour must be in 0..23  Traceback (most recent call last):  File '/home/fcee9ba5615b0b74fc3ba39ec9a789fd.py', line 21, in   print(time(hour='23')) TypeError: an integer is required (got type str) 

예시 2: 시, 분, 초, 마이크로초 가져오기

시간 객체를 생성한 후 해당 속성을 별도로 인쇄할 수도 있습니다.

파이썬3




from> datetime> import> time> Time> => time(> 11> ,> 34> ,> 56> )> print> (> 'hour ='> , Time.hour)> print> (> 'minute ='> , Time.minute)> print> (> 'second ='> , Time.second)> print> (> 'microsecond ='> , Time.microsecond)>

산출:

hour = 11 minute = 34 second = 56 microsecond = 0 

예제 3: Time 객체를 문자열로 변환

isoformat() 메소드를 사용하여 시간 객체를 문자열로 변환할 수 있습니다.

파이썬3




from> datetime> import> time> # Creating Time object> Time> => time(> 12> ,> 24> ,> 36> ,> 1212> )> # Converting Time object to string> Str> => Time.isoformat()> print> (> 'String Representation:'> ,> Str> )> print> (> type> (> Str> ))>

산출

String Representation: 12:24:36.001212 

시간 클래스 메소드 목록

기능 이름

설명

dst() tzinfo.dst()가 tzinfo가 None이 아닌 경우를 반환합니다.
fromisoformat() 시간의 문자열 표현에서 시간 객체를 반환합니다.
아이소포맷() 시간 객체에서 시간의 문자열 표현을 반환합니다.
바꾸다() 주어진 매개변수로 시간 객체의 값을 변경합니다.
strftime() 주어진 형식으로 시간의 문자열 표현을 반환합니다.
tzname() tzinfo.tzname()이 tzinfo가 None이 아닌 경우를 반환합니다.
utcoffset() tzinfo.utcffsets()가 tzinfo가 None이 아닌 경우를 반환합니다.

Python 날짜/시간 클래스

그만큼 날짜/시간 클래스 날짜와 시간에 대한 정보가 모두 포함되어 있습니다. 날짜 객체와 마찬가지로 datetime은 현재 양력이 양방향으로 확장된다고 가정합니다. 시간 객체와 마찬가지로 datetime은 하루가 정확히 3600*24초라고 가정합니다.

생성자 구문:

클래스 datetime.datetime(년, 월, 일, 시=0, 분=0, 초=0, 마이크로초=0, tzinfo=없음, *, 접기=0)

연도, 월, 일 인수는 필수입니다. tzinfo는 None일 수 있습니다. 나머지 모든 속성은 다음 범위의 정수여야 합니다.

  • MINYEAR <= 연도 <= MAXYEAR
  • 1 <= 월 <= 12
  • 1 <= 일 <= 해당 월 및 연도의 일 수
  • 0 <= 시간 < 24
  • 0 <= 분 < 60
  • 0 <= 초 < 60
  • 0 <= 마이크로초 < 1000000
  • [0, 1]로 접기

메모 – 정수가 아닌 인수를 전달하면 TypeError가 발생하고 범위 밖의 인수를 전달하면 ValueError가 발생합니다.

Python에서 DateTime을 나타내는 DateTime 객체

파이썬3




# Python program to> # demonstrate datetime object> from> datetime> import> datetime> # Initializing constructor> a> => datetime(> 1999> ,> 12> ,> 12> )> print> (a)> # Initializing constructor> # with time parameters as well> a> => datetime(> 1999> ,> 12> ,> 12> ,> 12> ,> 12> ,> 12> ,> 342380> )> print> (a)>

산출:

1999-12-12 00:00:00 1999-12-12 12:12:12.342380 

연도, 월, 시, 분, 타임스탬프 가져오기

DateTime 객체를 생성한 후 해당 속성을 별도로 인쇄할 수도 있습니다.

파이썬3




from> datetime> import> datetime> a> => datetime(> 1999> ,> 12> ,> 12> ,> 12> ,> 12> ,> 12> )> print> (> 'year ='> , a.year)> print> (> 'month ='> , a.month)> print> (> 'hour ='> , a.hour)> print> (> 'minute ='> , a.minute)> print> (> 'timestamp ='> , a.timestamp())>

산출:

year = 1999 month = 12 hour = 12 minute = 12 timestamp = 945000732.0 

현재 날짜 및 시간

Datetime.now() 함수를 사용하여 현재 날짜와 시간을 인쇄할 수 있습니다. now() 함수는 현재 현지 날짜와 시간을 반환합니다.

파이썬3




from> datetime> import> datetime> # Calling now() function> today> => datetime.now()> print> (> 'Current date and time is'> , today)>

산출:

Current date and time is 2019-10-25 11:12:11.289834 

Python 날짜/시간을 문자열로 변환

다음을 사용하여 Python에서 Datetime을 문자열로 변환할 수 있습니다. 날짜시간.strftime 및 datetime.isoformat 메소드.

파이썬3




from> datetime> import> datetime as dt> # Getting current date and time> now> => dt.now()> string> => dt.isoformat(now)> print> (string)> print> (> type> (string))>

산출

2021-08-19T18:13:25.346259 

Datetime 클래스 메서드 목록

기능 이름

설명

시간대() 시간대 정보가 포함된 DateTime 객체를 반환합니다.
결합하다() 날짜와 시간 객체를 결합하고 DateTime 객체를 반환합니다.
c시간() 날짜와 시간의 문자열 표현을 반환합니다.
날짜() Date 클래스 객체를 반환합니다.
fromisoformat() 날짜 및 시간의 문자열 표현에서 날짜/시간 객체를 반환합니다.
서수() 1년 1월 1일의 서수가 1인 역산 그레고리력 서수에서 날짜 객체를 반환합니다. 시, 분, 초, 마이크로초는 0입니다.
타임스탬프() POSIX 타임스탬프에서 날짜 및 시간 반환
아이소캘린더() 튜플 연도, 주, 요일을 반환합니다.
아이소포맷() 날짜와 시간의 문자열 표현을 반환합니다.
isoweekday() 월요일이 1이고 일요일이 7인 경우 요일을 정수로 반환합니다.
지금() tz 매개변수를 사용하여 현재 현지 날짜 및 시간을 반환합니다.
바꾸다() DateTime 객체의 특정 속성을 변경합니다.
strftime() 주어진 형식으로 DateTime 객체의 문자열 표현을 반환합니다.
문자열 시간() 날짜 문자열에 해당하는 DateTime 객체를 반환합니다.
시간() Time 클래스 객체를 반환합니다.
타임튜플() time.struct_time 유형의 객체를 반환합니다.
타임츠() Time 클래스 객체를 반환합니다.
오늘() tzinfo를 None으로 사용하여 로컬 DateTime을 반환합니다.
토서수() 1년 1월 1일이 서수 1인 날짜의 역산 그레고리력 서수를 반환합니다.
tzname() 시간대의 이름을 반환합니다.
utcfrom타임스탬프() POSIX 타임스탬프에서 UTC를 반환합니다.
utcoffset() UTC 오프셋을 반환합니다.
유트나우() 현재 UTC 날짜 및 시간을 반환합니다.
주일() 월요일이 0이고 일요일이 6인 경우 요일을 정수로 반환합니다.

Python Timedelta 클래스

Python timedelta 클래스는 날짜 차이를 계산하는 데 사용되며 Python에서 날짜 조작에도 사용할 수 있습니다. 날짜 조작을 수행하는 가장 쉬운 방법 중 하나입니다.

생성자 구문:

클래스 datetime.timedelta(일=0, 초=0, 마이크로초=0, 밀리초=0, 분=0, 시간=0, 주=0)
반품 : 날짜

DateTime 객체에 일 추가

timedelta 기능 데모

파이썬3




from> datetime> import> datetime, timedelta> # Using current time> ini_time_for_now> => datetime.now()> # printing initial_date> print> (> 'initial_date'> ,> str> (ini_time_for_now))> # Calculating future dates> # for two years> future_date_after_2yrs> => ini_time_for_now> +> timedelta(days> => 730> )> future_date_after_2days> => ini_time_for_now> +> timedelta(days> => 2> )> # printing calculated future_dates> print> (> 'future_date_after_2yrs:'> ,> str> (future_date_after_2yrs))> print> (> 'future_date_after_2days:'> ,> str> (future_date_after_2days))>

산출:

initial_date 2019-10-25 12:01:01.227848 future_date_after_2yrs: 2021-10-24 12:01:01.227848 future_date_after_2days: 2019-10-27 12:01:01.227848 

두 날짜와 시간의 차이

이 클래스를 사용하면 날짜 및 시간 차이도 찾을 수 있습니다.

파이썬3




# Timedelta function demonstration> from> datetime> import> datetime, timedelta> # Using current time> ini_time_for_now> => datetime.now()> # printing initial_date> print> (> 'initial_date'> ,> str> (ini_time_for_now))> # Some another datetime> new_final_time> => ini_time_for_now> +> > > timedelta(days> => 2> )> # printing new final_date> print> (> 'new_final_time'> ,> str> (new_final_time))> # printing calculated past_dates> print> (> 'Time difference:'> ,> str> (new_final_time> -> > ini_time_for_now))>

산출:

initial_date 2019-10-25 12:02:32.799814 new_final_time 2019-10-27 12:02:32.799814 Time difference: 2 days, 0:00:00 

Timedelta 클래스에서 지원하는 작업

운영자

설명

추가(+) 두 개의 timedelta 객체를 추가하고 반환합니다.
빼기(-) 두 개의 timedelta 객체를 빼고 반환합니다.
곱셈(*) timedelta 객체에 float 또는 int를 곱합니다.
분할 (/) timedelta 객체를 float 또는 int로 나눕니다.
층구분(//) timedelta 객체를 float 또는 int로 나누고 출력의 Floor 값의 int를 반환합니다.
모듈(%) 두 개의 timedelta 객체를 나누고 나머지를 반환합니다.
+(시간 델타) 동일한 timedelta 객체를 반환합니다.
-(시간 델타) -1*timedelta의 결과를 반환합니다.
절대(시간 델타) timedelta.days> 1=0이면 +(timedelta)를 반환하고 그렇지 않으면 -(timedelta)를 반환합니다.
str(타임델타) (+/-) 일[들], HH:MM:SS.UUUUUU 형식의 문자열을 반환합니다.
담당자(타임델타) 생성자 호출 형식으로 문자열 표현을 반환합니다.

Python에서 날짜/시간 형식 지정

날짜 표현은 장소에 따라 다를 수 있으므로 DateTime 형식을 지정하는 것이 매우 필요할 수 있습니다. 일부 국가에서는 yyyy-mm-dd일 수 있고 다른 국가에서는 dd-mm-yyyy일 수 있습니다. Python Datetime 형식을 지정하려면 strptime 및 strftime 함수를 사용할 수 있습니다.

Python 날짜/시간 strftime

strftime() 메서드는 지정된 날짜, 시간 또는 DateTime 객체를 지정된 형식의 문자열 표현으로 변환합니다.

Python 날짜/시간 형식

strftime() 함수를 시연하는 Python 프로그램

파이썬3




from> datetime> import> datetime as dt> # Getting current date and time> now> => dt.now()> print> (> 'Without formatting'> , now)> # Example 1> s> => now.strftime(> '%A %m %-Y'> )> print> (> ' Example 1:'> , s)> # Example 2> s> => now.strftime(> '%a %-m %y'> )> print> (> ' Example 2:'> , s)> # Example 3> s> => now.strftime(> '%-I %p %S'> )> print> (> ' Example 3:'> , s)> # Example 4> s> => now.strftime(> '%H:%M:%S'> )> print> (> ' Example 4:'> , s)>

산출

Without formatting 2021-08-19 18:16:25.881661 Example 1: Thursday 08 2021 Example 2: Thu 8 21 Example 3: 6 PM 25 Example 4: 18:16:25 

메모: 자세한 내용은 다음을 참조하세요. strftime() 메서드 .

Python DateTime strptime

strptime()은 주어진 문자열에서 DateTime 객체를 생성합니다.

예: 날짜시간 strptime

파이썬3




# import datetime module from datetime> from> datetime> import> datetime> > # consider the time stamps from a list in string> # format DD/MM/YY H:M:S.micros> time_data> => [> '25/05/99 02:35:8.023'> ,> '26/05/99 12:45:0.003'> ,> > '27/05/99 07:35:5.523'> ,> '28/05/99 05:15:55.523'> ]> > # format the string in the given format : day/month/year> # hours/minutes/seconds-micro seconds> format_data> => '%d/%m/%y %H:%M:%S.%f'> > # Using strptime with datetime we will format string> # into datetime> for> i> in> time_data:> > print> (datetime.strptime(i, format_data))>

산출

1999-05-25 02:35:08.023000 1999-05-26 12:45:00.003000 1999-05-27 07:35:05.523000 1999-05-28 05:15:55.523000 

파이썬 DateTime.tzinfo()

그만큼 datetime.now() 함수 시간대에 관한 정보가 포함되어 있지 않습니다. 현재 시스템 시간만 사용합니다. Tzinfo는 Python의 추상 기본 클래스입니다. 직접 인스턴스화할 수 없습니다. 구체적인 하위 클래스는 이 추상 클래스에서 파생되어야 하며 이 클래스에서 제공하는 메서드를 구현해야 합니다.

Python DateTime.tzinfo() 객체 목록

기능 이름

설명

dst() tzinfo.dst()가 tzinfo가 None이 아닌 경우를 반환합니다.
fromutc() 이 기능의 목적은 날짜 시간 데이터를 조정하는 것입니다.
자신의 현지 시간으로 동등한 DateTime을 반환합니다.
tzname() tzinfo.tzname()이 tzinfo가 None이 아닌 경우를 반환합니다.
utcoffset() tzinfo.utcffsets()가 tzinfo가 None이 아닌 경우를 반환합니다.

tzinfo 클래스 인스턴스는 DateTime 및 time 객체 생성자에 제공될 수 있습니다. 현지 시간을 UTC로 변환하거나 일광 절약 시간을 고려하는 등의 시나리오에 사용됩니다.

파이썬3




import> datetime as dt> from> dateutil> import> tz> tz_string> => dt.datetime.now(dt.timezone.utc).astimezone().tzname()> print> (> 'datetime.now() :'> , tz_string)> NYC> => tz.gettz(> 'Europe / Berlin'> )> dt1> => dt.datetime(> 2022> ,> 5> ,> 21> ,> 12> ,> 0> )> dt2> => dt.datetime(> 2022> ,> 12> ,> 21> ,> 12> ,> 0> , tzinfo> => NYC)> print> (> 'Naive Object :'> , dt1.tzname())> print> (> 'Aware Object :'> , dt2.tzname())>

산출:

datetime.now() : IST Naive Object : None Aware Object : None 

Python DateTime 시간대

특정 지역의 시간대에 따라 시간을 표시하려는 경우 DateTime의 시간대를 사용할 수 있습니다. 이 작업은 다음을 사용하여 수행할 수 있습니다. 피츠 모듈 파이썬의. 이 모듈은 날짜-시간 변환 기능을 제공하고 사용자가 국제 클라이언트 기반에 서비스를 제공하도록 돕습니다.

파이썬3




from> datetime> import> datetime> from> pytz> import> timezone> format> => '%Y-%m-%d %H:%M:%S %Z%z'> # Current time in UTC> now_utc> => datetime.now(timezone(> 'UTC'> ))> print> (now_utc.strftime(> format> ))> timezones> => [> 'Asia/Kolkata'> ,> 'Europe/Kiev'> ,> 'America/New_York'> ]> for> tzone> in> timezones:> > # Convert to Asia/Kolkata time zone> > now_asia> => now_utc.astimezone(timezone(tzone))> > print> (now_asia.strftime(> format> ))>

산출

2021-08-19 18:27:28 UTC+0000 2021-08-19 23:57:28 IST+0530 2021-08-19 21:27:28 EEST+0300 2021-08-19 14:27:28 EDT-0400