날짜 처리와 관련하여 Python은 표준 라이브러리 datetime, 타사 라이브러리 dateutil, arrow 등과 같은 많은 라이브러리를 제공합니다.
사용하기 전에 설치해야 합니다. pip install pendulum만 설치하면 됩니다.
사용법을 살펴보겠습니다. 첫 번째는 datetime, date, time 생성입니다.
import pendulum dt = pendulum.datetime( 2022, 3, 28, 20, 10, 30) print(dt.__class__) print(dt) """ <class 'pendulum.datetime.DateTime'> 2022-03-28T20:10:30+00:00 """ # 创建的对象是 DateTime 类型 # 并且带有时区,默认是 UTC # 我们可以换一个时区 dt = pendulum.datetime( 2022, 3, 28, 20, 10, 30, tz="Asia/Shanghai") print(dt) """ 2022-03-28T20:10:30+08:00 """ # 如果不想要时区,那么指定 tz=None dt = pendulum.datetime( 2022, 3, 28, 20, 10, 30, tz=None) print(dt) """ 2022-03-28T20:10:30 """ # 然后是 date 的创建 d = pendulum.date(2022, 3, 28) print(d.__class__) print(d) """ <class 'pendulum.date.Date'> 2022-03-28 """ # time 的创建 t = pendulum.time(20, 10, 30) print(t.__class__) print(t) """ <class 'pendulum.time.Time'> 20:10:30 """
날짜/시간을 생성하면 시간대는 기본적으로 UTC로 설정됩니다. 시간대를 원하지 않거나 시간대를 현지 시간대로 설정하려는 경우 Pendulum은 두 가지 방법도 제공합니다.
import pendulum # 创建 datetime 时设置为本地时区 # 还是调用了 pendulum.datetime 函数 # 但是 tz 被设置成了 pendulum.local_timezone() dt = pendulum.local( 2022, 3, 28, 20, 10, 30) print(dt) """ 2022-03-28T20:10:30+08:00 """ print(pendulum.local_timezone()) """ Timezone('Asia/Shanghai') """ # 创建 datetime 时不设置时区 # 内部也是调用了 pendulum.datetime 函数 # 但是 tz 为 None dt = pendulum.naive(2022, 3, 28, 20, 10, 30) print(dt) """ 2022-03-28T20:10:30 """
Then Pendulum은 현재 날짜/시간, 날짜 등을 생성하는 등 여러 가지 방법도 제공합니다.
import pendulum # 创建当前的 datetime # 默认是本地时区,但时区可以指定 dt = pendulum.now() print(dt) """ 2022-05-29T20:40:49.632182+08:00 """ # 创建当前的 date,但返回的仍是 datetime # 只不过时分秒均为 0,同样可以指定时区 dt = pendulum.today() print(dt) """ 2022-05-29T00:00:00+08:00 """ # 获取明天对应的 date # 返回的是 datetime,时分秒为 0 # 时区可以指定,默认是本地时区 dt = pendulum.tomorrow() print(dt) """ 2022-05-30T00:00:00+08:00 """ # 获取昨天对应的 date dt = pendulum.yesterday() print(dt) """ 2022-05-28T00:00:00+08:00 """
타임스탬프나 문자열을 기반으로 생성할 수도 있습니다.
import pendulum # 根据时间戳创建 dt1 = pendulum.from_timestamp(1653828466) dt2 = pendulum.from_timestamp(1653828466, tz=pendulum.local_timezone()) print(dt1) print(dt2) """ 2022-05-29T12:47:46+00:00 2022-05-29T20:47:46+08:00 """ # 根据字符串创建 dt1 = pendulum.parse("2020-05-03 12:11:33") dt2 = pendulum.parse("2020-05-03 12:11:33", tz=pendulum.local_timezone()) print(dt1) print(dt2) """ 2020-05-03T12:11:33+00:00 2020-05-03T12:11:33+08:00 """
날짜/시간, 날짜 및 시간 생성에 대해 이야기한 다음 핵심 부분인 지원하는 작업을 살펴보겠습니다.
Datetime 관련 작업
작업이 많아서 하나씩 소개하겠습니다.
import pendulum dt = pendulum.local( 2022, 3, 28, 20, 10, 30) # 获取 date 部分和 time 部分 print(dt.date()) print(dt.time()) """ 2022-03-28 20:10:30 """ # 替换掉 dt 的某部分,返回新的 datetime # 年月日时分秒、以及时区都可以替换 print(dt.replace(year=9999)) """ 9999-03-28T20:10:30+08:00 """ # 转成时间戳 print(dt.timestamp()) """ 1648469430.0 """ # 返回年、月、日、时、分、秒、时区 print(dt.year, dt.month, dt.day) print(dt.hour, dt.minute, dt.second) print(dt.tz) """ 2022 3 28 20 10 30 Timezone('Asia/Shanghai') """
그런 다음 pendulum.DateTime 개체를 다양한 형식의 날짜 문자열로 변환할 수 있습니다.
import pendulum dt = pendulum.local( 2022, 3, 28, 20, 10, 30) # 下面四个最为常用 print("datetime:", dt.to_datetime_string()) print("date:", dt.to_date_string()) print("time:", dt.to_time_string()) print("iso8601:", dt.to_iso8601_string()) """ datetime: 2022-03-28 20:10:30 date: 2022-03-28 time: 20:10:30 iso8601: 2022-03-28T20:10:30+08:00 """ # 当然还支持很多其它格式,不过用的不多 # 随便挑几个吧 print("atom:", dt.to_atom_string()) print("rss:", dt.to_rss_string()) print("w3c:", dt.to_w3c_string()) print("cookie:", dt.to_cookie_string()) print("rfc822:", dt.to_rfc822_string()) """ atom: 2022-03-28T20:10:30+08:00 rss: Mon, 28 Mar 2022 20:10:30 +0800 w3c: 2022-03-28T20:10:30+08:00 rfc822: Mon, 28 Mar 22 20:10:30 +0800 """
때로는 현재 날짜가 어느 요일인지, 올해의 요일 등을 결정해야 하는 경우도 있습니다. Pendulum도 이를 패키지로 제공합니다.
import pendulum dt = pendulum.local( 2022, 3, 28, 20, 10, 30) # 返回星期几 # 注意:星期一到星期天分别对应 1 到 7 print(dt.isoweekday())# 1 # 返回一年当中的第几天 # 范围是 1 到 366 print(dt.day_of_year)# 87 # 返回一个月当中的第几天 print(dt.days_in_month)# 31 # 返回一个月当中的第几周 print(dt.week_of_month)# 5 # 返回一年当中的第几周 print(dt.week_of_year)# 13 # 是否是闰年 print(dt.is_leap_year())# False
마지막 단계는 날짜 연산입니다. 이것이 Pendulum의 가장 강력한 부분입니다. 왜 강력한지는 시연을 해본 후에 알 수 있습니다.
import pendulum dt = pendulum.local( 2022, 3, 30, 20, 10, 30) # 返回下一个月的今天 print(dt.add(months=1)) """ 2022-04-30T20:10:30+08:00 """ # 返回上一个月的今天 # 但是上一个月是 2 月,并且是平年 # 所以最多 28 天 print(dt.add(months=-1)) """ 2022-02-28T20:10:30+08:00 """ # 我们看到处理的非常完美 # 该方法的原型如下,年月日时分秒都是支持的,当然还有星期也支持 """ def add( self, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0, ): """
Python의 내장 모듈 datetime과 마찬가지로 날짜를 추가할 때 다음 주, 다음 달, 내년의 날짜를 계산할 수 없습니다. 그리고 진자는 다루기 쉽기 때문에 제가 가장 좋아하는 점입니다.
물론, add의 양수 값은 날짜를 뒤로 이동하는 것과 같습니다. 음수 값은 날짜를 앞당기는 것과 같습니다.
그런 다음 두 날짜를 뺄 수도 있습니다.
import pendulum dt1 = pendulum.local( 2021, 1, 20, 11, 22, 33) dt2 = pendulum.local( 2022, 3, 30, 20, 10, 30) period = dt2 - dt1 # 返回的是 Period 对象 # 相当于 datetime 模块里面的 timedelta print(period.__class__) """ <class 'pendulum.period.Period'> """ # 但是功能方面,Period 要强大很多 # 两者差了多少年 print(period.in_years())# 1 # 两者差了多少个月 print(period.in_months())# 14 # 两者差了多少个星期 print(period.in_weeks())# 62 # 两者差了多少天 print(period.in_days())# 434 # 两者差了多少个小时 print(period.in_hours())# 10424 # 两者差了多少分钟 print(period.in_minutes())# 625487 # 两者差了多少秒 print(period.in_seconds())# 37529277
이 함수는 매우 강력합니다. Python datetime 모듈의 timedelta는 최대 두 날짜 간의 일수 차이만 계산할 수 있지만 여기서는 연, 월, 일이 가능합니다. , 시, 분 또는 초.
위 내용은 이 글의 내용입니다. 물론 Pendulum의 기능은 위에서 언급한 것보다 더 많습니다. 관심이 있는 경우 공식 웹사이트를 참조할 수 있지만 가장 일반적으로 사용되는 기능은 다음과 같습니다.
위 내용은 Python 날짜 라이브러리 진자를 사용하여 날짜와 시간 처리의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

inpython, youappendElementStoalistUsingTheAppend () 메소드 1) useappend () forsinglelements : my_list.append (4) .2) useextend () 또는 = formultiplementements : my_list.extend (other_list) 또는 my_list = [4,5,6] .3) useinsert () forspecificpositions : my_list.insert (1,5) .Bearware

Shebang 문제를 디버깅하는 방법에는 다음이 포함됩니다. 1. Shebang 라인을 확인하여 스크립트의 첫 번째 줄인지 확인하고 접두사 공간이 없는지 확인하십시오. 2. 통역 경로가 올바른지 확인하십시오. 3. 통역사에게 직접 전화하여 스크립트를 실행하여 Shebang 문제를 분리하십시오. 4. Strace 또는 Trusts를 사용하여 시스템 호출을 추적합니다. 5. Shebang에 대한 환경 변수의 영향을 확인하십시오.

pythonlistscanbemanipatedusingseveralmethodstoremoveElements : 1) geremove () methodremove () methodeMovestHefirstoccurrence.2) thePop () methodRemovesAndReTurnSanElementatAgivenIndex.3) THEDELSTATEMENTCANREMORENDEX.4) LESTCORHENSCREC

PythonlistscanstoreAnydatataTATY, 문자열, 부유물, 부울, 기타 목록 및 디터 시어

pythonlistssupportnumouseOperations : 1) addingElementSwitHappend (), extend (), andinsert ()

다음 단계를 통해 Numpy를 사용하여 다차원 배열을 만들 수 있습니다. 1) Numpy.array () 함수를 사용하여 NP.Array ([[1,2,3], [4,5,6]]과 같은 배열을 생성하여 2D 배열을 만듭니다. 2) np.zeros (), np.ones (), np.random.random () 및 기타 함수를 사용하여 특정 값으로 채워진 배열을 만듭니다. 3) 서브 어레이의 길이가 일관되고 오류를 피하기 위해 배열의 모양과 크기 특성을 이해하십시오. 4) NP.Reshape () 함수를 사용하여 배열의 모양을 변경하십시오. 5) 코드가 명확하고 효율적인지 확인하기 위해 메모리 사용에주의를 기울이십시오.

BroadcastingInnumpyIsamethodtoperformoperationsonArraysoffferentShapesByAutomicallyAligningThem.itsimplifiesCode, enourseadability, andboostsperformance.here'showitworks : 1) smalraysarepaddedwithonestomatchdimenseare

forpythondatastorage, chooselistsforflexibilitywithmixeddatatypes, array.arrayformemory-effic homogeneousnumericaldata, andnumpyarraysforadvancednumericalcomputing.listsareversatilebutlessefficipforlargenumericaldatasets.arrayoffersamiddlegro


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

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

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음
