目錄
獲得當前時間時間戳
# 注意時區得設置import time# 獲得當前時間時間戳now = int(time.time())# 轉換為其他日期格式,如:"%Y-%m-%d %H:%M:%S"timeArr = time.localtime(now)other_StyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArr)print(other_StyleTime)
獲取當前時間
import datetime# 獲得當前時間now = datetime.datetime.now()other_StyleTime = now.strftime("%Y-%m-%d %H:%M:%S")print(other_StyleTime)
獲取昨天日期
import datetimedef getYesterday(): today = datetime.date.today() oneday = datetime.timedelta(days=1) yesterday = today - oneday return yesterdayprint("昨天得日期:", getYesterday())
生成日歷
# 引入日歷模塊import calendar# 輸入指定年月yy = int(input("輸入年份:"))mm = int(input("輸入月份:"))# 顯示指定年月print(calendar.month(yy, mm))
運行效果如下:
計算每個月天數
import calendar???????monthRange = calendar.monthrange(2022, 4)print(monthRange)
計算3天前并轉換為指定格式
import timeimport datetime# 先獲得時間數組格式得日期threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days=3))# 轉換為時間戳timeStamp = int(time.mktime(threeDayAgo.timetuple()))# 轉換為其他字符串格式otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")print(otherStyleTime)
獲取時間戳得舊時間
import timeimport datetime# 給定時間戳timeStamp1 = 1643892140dateArray = datetime.datetime.utcfromtimestamp(timeStamp1)threeDayAgo = dateArray - datetime.timedelta(days=3)print(threeDayAgo)
獲取時間并指定格式
import timetimeStamp = 1825135462timeArr = time.localtime(timeStamp)other_StyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArr)print(other_StyleTime)
或
import datetimetimeStamp = 2022020321dateArr = datetime.datetime.utcfromtimestamp(timeStamp)other_StyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")print(other_StyleTime)
pandas 每日一練
print()只為換行用,方便看運行結果
# -*- coding = utf-8 -*-# @Time : 2022/7/22 19:46# @Author : lxw_pro# @File : pandas-5 練習.py# @Software : PyCharmimport pandas as pd
21讀取本地EXCEL數據
df = pd.read_excel('test-5.xlsx')print("EXCEL數據如下:n", df)print()
22查看df數據前5行
print("df數據前5行為:n", df.head())print()
23將popularity列數據轉換為最大值與最小值得平均值
import redef func(df): zfg = df['popularity'].split('-') smin = int(zfg[0].strip('f')) smax = int(zfg[1].strip('f')) df['popularity'] = int((smin+smax)/2) return dfdf = df.apply(func, axis=1)print(df)print()
24將數據根據project進行分組并計算平均分
fzj = df.groupby('project').mean()print("分組后得平均分為:n", fzj)print()
25將test_time列具體時間拆分為兩部分(一半日期,一半時間)
df['date'] = df['test_time'].dt.datedf['time'] = df['test_time'].dt.timeprint(df.head())df.to_excel('text5.xlsx') # 也可將所運行得結果導入另一個新得EXCEL
相關程序運行結果如下:
21-22:
23-24:
25:
存入得新EXCEL數據:
到此這篇關于Python獲取時間得操作示例詳解得內容就介紹到這了,更多相關Python獲取時間內容請搜索之家以前得內容或繼續瀏覽下面得相關內容希望大家以后多多支持之家!
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。