>  기사  >  백엔드 개발  >  Python 날짜 및 시간 사용법에 대한 요약

Python 날짜 및 시간 사용법에 대한 요약

WBOY
WBOY앞으로
2023-04-13 10:58:081336검색

시간은 의심할 여지 없이 삶의 모든 측면에서 가장 중요한 요소 중 하나이므로 시간을 기록하고 추적하는 것이 매우 중요해집니다. Python에서는 내장 라이브러리를 통해 날짜와 시간을 추적할 수 있습니다. 오늘은 Python의 날짜와 시간에 대해 소개하고, time 및 datetime 모듈을 사용하여 날짜와 시간을 찾고 수정하는 방법을 알아봅니다.

Python에서 날짜와 시간을 처리하는 모듈

Python에서는 날짜와 시간을 쉽게 얻고 수정할 수 있는 시간 및 날짜/시간 모듈을 하나씩 살펴보겠습니다.

시간 모듈

이 모듈에는 시간을 사용하여 다양한 작업을 수행하는 데 필요한 모든 시간 관련 기능이 포함되어 있으며 다양한 목적에 필요한 시계 유형에 액세스할 수도 있습니다.

내장 기능:

시간 모듈의 몇 가지 중요한 내장 기능을 설명하는 아래 표를 살펴보십시오.

이 클래스를 인수로 사용하거나 출력으로 반환합니다. localtime()은 에포크 이후 경과된 초 수를 인수로 사용하고 날짜와 시간을 시간으로 반환합니다. struct_time 형식

function

Description

time()

epoch 이후 경과된 초 수를 반환합니다.

ctime()

인수로 초과 몇 초를 걸고 현재 날짜와 시간을 반환합니다

sleep ()

주어진 시간에 대한 스레드의 실행

time.struct_time class

🎜gmtime()🎜

localtime()과 유사하며 시간을 반환합니다. UTC 형식의 struct_time

mktime()

ocaltime()의 역수입니다. 9개의 매개변수가 포함된 튜플을 가져오고 epoch pas 출력 이후 경과된 초 수를 반환합니다.

asctime()

9개의 매개변수가 포함된 튜플을 가져오고 동일한 매개변수를 나타내는 문자열을 반환합니다.

strftime()

9개의 매개변수가 포함된 튜플을 가져오고 사용된 형식 코드를 기반으로 동일한 매개변수를 나타내는 문자열을 반환합니다.

strptime()

문자열을 분석하여 시간에 맞춰 반환합니다. struct_time 형식

코드 형식 지정:

예제를 통해 각 기능을 설명하기 전에 코드 형식을 지정하는 모든 합법적인 방법을 살펴보겠습니다.

예 %a%A %b%B%c

평일(짧은 버전)

Mon

평일(풀 버전)

월요일

월(짧은 버전)

Aug

월(전체 버전)

8월

현지 날짜 및 시간 버전

Tue Aug 23 1:31:40 2019

%d

월의 날짜를 나타냅니다(01-31)

07

%f

마이크로초

000000-999999

%H

시간(00-23)

15

%I

시간(00-11 )

3

%j

연중일

235

%m

월 번호(01-12)

07

%M

분(00-59)

44

%p

AM / PM

AM

%S

초(00-59)

23

%U

일요일부터 시작하는 주 수(00-53)

12

%w

주의 요일 수

Monday (1)

%W

월요일부터 시작하는 주 수( 00-53)

34

%x

현지 날짜

06/07/22

%X

현지 시간

12:30:45

%y

연도(짧은 버전)

22

%Y

연도(풀 버전)

2022

%z

UTC 오프셋

+0100

%Z

시간대

CST

%%

% 캐릭터

%

struct_time 클래스에는 다음 속성이 있습니다. .., 2019년, …, 9999

ㅋㅋㅋ 0-23

tm_min

0 -59

tm_sec

0-61

tm_wday

0-6(월요일은 0)

tm_yday

1-366

tm_isdst

0, 1, -1    (일광 절약 시간, 알 수 없는 경우 -1)

이제 시간 모듈의 몇 가지 예를 살펴보겠습니다.

시간 모듈을 사용하여 날짜와 시간 찾기

위 표에 설명된 내장 함수와 형식 지정 코드를 사용하면 Python에서 날짜와 시간을 쉽게 얻을 수 있습니다.

import time
#time
a=time.time() #total seconds since epoch
print("Seconds since epoch :",a,end='n----------n')
#ctime
print("Current date and time:")
print(time.ctime(a),end='n----------n') 
#sleep
time.sleep(1) #execution will be delayed by one second
#localtime
print("Local time :")
print(time.localtime(a),end='n----------n')
#gmtime
print("Local time in UTC format :")
print(time.gmtime(a),end='n-----------n')
#mktime
b=(2019,8,6,10,40,34,1,218,0)
print("Current Time in seconds :")
print( time.mktime(b),end='n----------n')
#asctime
print("Current Time in local format :")
print( time.asctime(b),end='n----------n')
#strftime
c = time.localtime() # get struct_time
d = time.strftime("%m/%d/%Y, %H:%M:%S", c)
print("String representing date and time:")
print(d,end='n----------n')
#strptime
print("time.strptime parses string and returns it in struct_time format :n")
e = "06 AUGUST, 2019"
f = time.strptime(e, "%d %B, %Y")
print(f)

출력:

Seconds since epoch : 1565070251.7134922
———-
Current date and time:
Tue Aug 6 11:14:11 2019
———-
Local time :
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=11, tm_min=14, tm_sec=11, tm_wday=1, tm_yday=218, tm_isdst=0)
———-
Local time in UTC format :
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=5, tm_min=44, tm_sec=11, tm_wday=1, tm_yday=218, tm_isdst=0)
———–
Current Time in seconds :
1565068234.0
———-
Current Time in local format :
Tue Aug 6 10:40:34 2019
———-
String representing date and time:
08/06/2019, 11:14:12
———-
time.strptime parses string and returns it in struct_time format :

time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=218, tm_isdst=-1)

datetime 모듈

time 모듈과 유사하게 datetime 모듈에는 날짜와 시간을 처리하는 데 필요한 모든 메서드가 포함되어 있습니다.

내장 기능:

다음 표에서는 이 모듈의 몇 가지 중요한 기능을 소개합니다. ()

날짜시간 of Constructor

datetime.today()

현재 현지 날짜와 시간을 반환합니다

datetime.now()

현재 현지 날짜와 시간을 반환합니다

date()

는 연도, 월, 일을 매개변수로 취하고 해당 날짜를 생성합니다.

time()

은 시, 분, 초, 마이크로초 및 tzinfo를 매개변수로 취하고 해당 날짜를 생성합니다

date.fromtimestamp()

초를 변환하여 해당 날짜와 시간을 반환합니다

timedelta()

它是不同日期或时间之间的差异(持续时间)

使用 datetime 查找日期和时间

现在,让我们尝试实现这些函数,以使用datetime模块在 Python 中查找日期和时间。

import datetime
#datetime constructor
print("Datetime constructor:n")
print(datetime.datetime(2019,5,3,8,45,30,234),end='n----------n')
 
#today
print("The current date and time using today :n")
print(datetime.datetime.today(),end='n----------n')
 
#now
print("The current date and time using today :n")
print(datetime.datetime.now(),end='n----------n')
 
#date
print("Setting date :n")
print(datetime.date(2019,11,7),end='n----------n')

#time
print("Setting time :n")
print(datetime.time(6,30,23),end='n----------n')
 
#date.fromtimestamp
print("Converting seconds to date and time:n")
print(datetime.date.fromtimestamp(23456789),end='n----------n')
 
#timedelta
b1=datetime.timedelta(days=30, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=4, weeks=8)
b2=datetime.timedelta(days=3, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=4, weeks=8)
b3=b2-b1
print(type(b3))
print("The resultant duration = ",b3,end='n----------n')
 
#attributes
a=datetime.datetime.now() #1
print(a)
print("The year is :",a.year)
 
print("Hours :",a.hour)

Output:

Datetime constructor:

2019-05-03 08:45:30.000234
———-
The current date and time using today :

2019-08-06 13:09:56.651691
———-
The current date and time using today :

2019-08-06 13:09:56.651691
———-
Setting date :

2019-11-07
———-
Setting time :

06:30:23
———-
Converting seconds to date and time:
1970-09-29
———-
<class ‘datetime.timedelta’>
The resultant duration = -27 days, 0:00:00
———-
2019-08-06 13:09:56.653694
The year is : 2019
Hours : 13

위 내용은 Python 날짜 및 시간 사용법에 대한 요약의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 51cto.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제