Python鏃ユ湡鍑芥暟澶у叏鍙婄敤娉曠ず渚

浣滆咃細灏忔柊妯℃澘 鏃堕棿锛2023-06-30 12:06:22 闃呰鏁帮細199浜洪槄璇

Python鎻愪緵浜嗕竴绯诲垪鏃ユ湡鍑芥暟鏉ュ鐞嗘棩鏈熷拰鏃堕棿锛屽畠浠彲浠ュ府鍔╂垜浠交鏉惧鐞嗘棩鏈熷拰鏃堕棿鐨勬搷浣溿備笅闈㈡垜浠皢浠嬬粛涓浜涘父鐢ㄧ殑Python鏃ユ湡鍑芥暟锛屼互鍙婂畠浠殑鐢ㄦ硶绀轰緥銆

datetime.date()鍑芥暟

datetime.date()鍑芥暟鍙互鐢ㄦ潵鑾峰彇褰撳墠鐨勬棩鏈燂紝瀹冭繑鍥炰竴涓猟ate瀵硅薄锛屽寘鍚勾銆佹湀銆佹棩淇℃伅锛屼緥濡傦細

import datetimedate= datetime.date.today()print(date)# 2020-04-16

datetime.datetime()鍑芥暟

datetime.datetime()鍑芥暟鍙互鐢ㄦ潵鑾峰彇褰撳墠鐨勬棩鏈熷拰鏃堕棿锛屽畠杩斿洖涓涓猟atetime瀵硅薄锛屽寘鍚勾銆佹湀銆佹棩銆佹椂銆佸垎銆佺淇℃伅锛屼緥濡傦細

import datetimedate= datetime.datetime.now()print(date)# 2020-04-16 10:47:59.054797

datetime.timedelta()鍑芥暟

datetime.timedelta()鍑芥暟鍙互鐢ㄦ潵鑾峰彇涓や釜鏃ユ湡涔嬮棿鐨勫樊鍊硷紝瀹冭繑鍥炰竴涓猼imedelta瀵硅薄锛岃〃绀轰袱涓棩鏈熶箣闂寸殑鏃堕棿宸紝渚嬪锛

import datetime date1 = datetime.date(2020, 4, 10) date2 = datetime.date(2020, 4, 16) diff = date2 - date1 print(diff)# 6 days, 0:00:00

datetime.strptime()鍑芥暟

datetime.strptime()鍑芥暟鍙互鐢ㄦ潵灏嗗瓧绗︿覆绫诲瀷鐨勬棩鏈熻浆鎹负datetime瀵硅薄锛屽畠鎺ユ敹涓や釜鍙傛暟锛岀涓涓弬鏁版槸鏃ユ湡瀛楃涓诧紝绗簩涓弬鏁版槸鏃ユ湡鏍煎紡锛屼緥濡傦細

import datetime date_str ='2020-04-16'date_format ='%Y-%m-%d'date= datetime.datetime.strptime(date_str, date_format)print(date)# 2020-04-16 00:00:00

datetime.strftime()鍑芥暟

datetime.strftime()鍑芥暟鍙互鐢ㄦ潵灏哾atetime瀵硅薄杞崲涓哄瓧绗︿覆绫诲瀷鐨勬棩鏈燂紝瀹冩帴鏀朵竴涓弬鏁帮紝鍗虫棩鏈熸牸寮忥紝渚嬪锛

importdatetime date = datetime.datetime.now() date_format ='%Y-%m-%d %H:%M:%S'date_str = date.strftime(date_format)print(date_str)# 2020-04-16 10:51:55

datetime.weekday()鍑芥暟

datetime.weekday()鍑芥暟鍙互鐢ㄦ潵鑾峰彇鎸囧畾鏃ユ湡鐨勬槦鏈熷嚑锛屽畠杩斿洖涓涓暣鏁帮紝0琛ㄧず鏄熸湡涓锛1琛ㄧず鏄熸湡浜岋紝浠ユ绫绘帹锛屼緥濡傦細

importdatetime date = datetime.date(2020,4,16) weekday = date.weekday()print(weekday)# 3

datetime.isoweekday()鍑芥暟

datetime.isoweekday()鍑芥暟鍙互鐢ㄦ潵鑾峰彇鎸囧畾鏃ユ湡鐨処SO鏄熸湡鍑狅紝瀹冭繑鍥炰竴涓暣鏁帮紝1琛ㄧず鏄熸湡涓锛2琛ㄧず鏄熸湡浜岋紝浠ユ绫绘帹锛屼緥濡傦細

importdatetime date = datetime.date(2020,4,16) weekday = date.isoweekday()print(weekday)# 4

datetime.timestamp()鍑芥暟

datetime.timestamp()鍑芥暟鍙互鐢ㄦ潵鑾峰彇鎸囧畾鏃ユ湡鐨勬椂闂存埑锛屽畠杩斿洖涓涓诞鐐规暟锛岃〃绀轰粠1970骞1鏈1鏃ュ埌鎸囧畾鏃ユ湡鐨勭鏁帮紝渚嬪锛

importdatetime date = datetime.datetime.now() timestamp = date.timestamp()print(timestamp)# 1587015078.71186

datetime.fromtimestamp()鍑芥暟

datetime.fromtimestamp()鍑芥暟鍙互鐢ㄦ潵灏嗘椂闂存埑杞崲涓篸atetime瀵硅薄锛屽畠鎺ユ敹涓涓弬鏁帮紝鍗虫椂闂存埑锛屼緥濡傦細

import datetimetimestamp=1587015078.71186date=datetime.datetime.fromtimestamp(timestamp) print(date) #2020-04-1610:57:58.71186

浠ヤ笂灏辨槸锛孭ython鎻愪緵浜嗕赴瀵岀殑鏃ユ湡鍑芥暟锛屽彲浠ュ府鍔╂垜浠交鏉惧鐞嗘棩鏈熷拰鏃堕棿鐨勬搷浣溿


浠ヤ笂灏辨槸Python鏃ユ湡鍑芥暟澶у叏鍙婄敤娉曠ず渚嬬殑璇︾粏鍐呭锛屾洿澶氫俊鎭鍏虫敞OD浜戝叾瀹冪浉鍏虫枃绔狅紒



鏈枃URL锛http://www.odweb.cn/news_show.html?id=281