Python 날짜 및 시간 사용법에 대한 요약
시간은 의심할 여지 없이 삶의 모든 측면에서 가장 중요한 요소 중 하나이므로 시간을 기록하고 추적하는 것이 매우 중요해집니다. Python에서는 내장 라이브러리를 통해 날짜와 시간을 추적할 수 있습니다. 오늘은 Python의 날짜와 시간에 대해 소개하고, time 및 datetime 모듈을 사용하여 날짜와 시간을 찾고 수정하는 방법을 알아봅니다.
Python에서 날짜와 시간을 처리하는 모듈
Python에서는 날짜와 시간을 쉽게 얻고 수정할 수 있는 시간 및 날짜/시간 모듈을 하나씩 살펴보겠습니다.
시간 모듈
이 모듈에는 시간을 사용하여 다양한 작업을 수행하는 데 필요한 모든 시간 관련 기능이 포함되어 있으며 다양한 목적에 필요한 시계 유형에 액세스할 수도 있습니다.
내장 기능:
시간 모듈의 몇 가지 중요한 내장 기능을 설명하는 아래 표를 살펴보십시오.
function |
Description |
time() |
epoch 이후 경과된 초 수를 반환합니다. |
ctime() |
인수로 초과 몇 초를 걸고 현재 날짜와 시간을 반환합니다 |
sleep () |
주어진 시간에 대한 스레드의 실행 |
time.struct_time class |
| 이 클래스를 인수로 사용하거나 출력으로 반환합니다.
localtime() | 은 에포크 이후 경과된 초 수를 인수로 사용하고 날짜와 시간을 시간으로 반환합니다. struct_time 형식 |
🎜gmtime()🎜 | localtime()과 유사하며 시간을 반환합니다. UTC 형식의 struct_time |
mktime() |
ocaltime()의 역수입니다. 9개의 매개변수가 포함된 튜플을 가져오고 epoch pas 출력 이후 경과된 초 수를 반환합니다. |
asctime() |
9개의 매개변수가 포함된 튜플을 가져오고 동일한 매개변수를 나타내는 문자열을 반환합니다. |
strftime() |
9개의 매개변수가 포함된 튜플을 가져오고 사용된 형식 코드를 기반으로 동일한 매개변수를 나타내는 문자열을 반환합니다. |
strptime() |
문자열을 분석하여 시간에 맞춰 반환합니다. struct_time 형식 |
코드 형식 지정:
예제를 통해 각 기능을 설명하기 전에 코드 형식을 지정하는 모든 합법적인 방법을 살펴보겠습니다.
평일(짧은 버전) | 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
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 모듈에는 날짜와 시간을 처리하는 데 필요한 모든 메서드가 포함되어 있습니다.
내장 기능:
다음 표에서는 이 모듈의 몇 가지 중요한 기능을 소개합니다. ()
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undress AI Tool
무료로 이미지를 벗다

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Stock Market GPT
더 현명한 결정을 위한 AI 기반 투자 연구

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

ClassMethodsInpyThonareBoundTotheClassandNottoinStances

asyncio.queue는 비동기 작업 간의 안전한 통신을위한 큐 도구입니다. 1. 생산자는 awaitqueue.put (항목)을 통해 데이터를 추가하고 소비자는 awaitqueue.get ()를 사용하여 데이터를 얻습니다. 2. 처리하는 각 항목의 경우 queue.task_done ()을 호출하여 모든 작업을 완료하려면 queue.join ()을 기다려야합니다. 3. 소비자가 중지하도록 통지하기 위해 최종 신호로 아무것도 사용하지 않습니다. 4. 여러 소비자 인 경우 작업을 취소하기 전에 다수의 종말 신호를 보내거나 모든 작업이 처리되었습니다. 5. 큐는 설정 최대 규모의 제한 용량을 지원하고, 작업을 자동으로 매달아주고 이벤트 루프를 차단하지 않으며, 프로그램이 마침내 칸치를 통과합니다.

정규 표현식은 문자열 검색, 매칭 및 조작을 위해 Re 모듈을 통해 Python으로 구현됩니다. 1. Re.search ()를 사용하여 전체 문자열에서 첫 번째 일치를 찾으십시오. re.match ()는 문자열의 시작 부분에서만 일치합니다. 2. 브래킷 ()을 사용하여 매칭 하위 그룹을 캡처하여 가독성을 향상시키기 위해 명명 될 수 있습니다. 3. re.findall ()은 비 겹치지 않는 모든 경기를 반환하고, re.finditer ()는 일치하는 객체의 반복기를 반환합니다. 4. re.sub ()는 일치하는 텍스트를 대체하고 동적 함수 교체를 지원합니다. 5. 일반적인 패턴에는 \ d, \ w, \ s 등이 포함됩니다. re.ignorecase, re.multiline, re.dotall, re를 사용할 수 있습니다.

원격 파이썬 응용 프로그램을 디버그하기 위해서는 디버시를 사용하고 포트 전달 및 경로 매핑을 구성해야합니다. 먼저 원격 시스템에 디버그피를 설치하고 포트 5678을 듣고 코드를 수정하고 SSH 터널을 통해 원격 포트를 로컬 영역으로 전달한 다음 Vscode의 시작에서 "AttachToremotePython"을 구성하고 LocalRoot 및 Remoter Path Mappings를 올바르게 설정하십시오. 마지막으로 응용 프로그램을 시작하고 디버거에 연결하여 원격 브레이크 포인트 디버깅, 가변 확인 및 코드 스테핑을 실현하십시오. 전체 프로세스는 디버시, 안전한 포트 전달 및 정확한 경로 일치에 따라 다릅니다.

indistpythonisinstalledbyrunningpython- versionorpython3-versionintherminal; ifnotinstalled, downloadfrompython.organdaddtopath.

useys.argvforsimpleargumentAccess, whereargumentsArmanially handledandnoautomaticalvalidationorhelpisprovided.2.useargparseforrobustinterfaces, asitsupportsautomatichelp, typechecking, 옵션 values.3.argparseisReccoccondendedCOCOCOCOPLECOPLECOPLECOPLECOPLECOCLEDOUCHECCOMEDOUCHECCOCOCOCOCOPLECOCLED

Python 스크립트를 실행하려면 Sublimetext의 빌드 시스템을 구성해야합니다. 1. 명령 줄에 Python이 설치되어 사용 가능한지 확인하십시오. 2. Sublimetext에서 새 빌드 시스템을 만들고 { "cmd": [ "python", "-u", "$ file"], "file_regex": "^[] file \"(...?) \ ", line ([0-9]*)", "셀렉터": & qu

installandandconfigurelspwithonlanguageSerpylspforide-likefeaturessuchassaferename, andgotodefinition.2.useBublimetext'SfindInfiles와 함께 whithwithwithwithwithwithforcarefulmanualeclortingAcrossfiles.3.intexextooltoolsliker
