網站首頁 編程語言 正文
將datetime64[ns]轉為字符串日期
將datetime64[ns]轉為字符串日期(“%Y-%m-%d”)最核心的用法是:
pandas.series.dt.strftime('%Y-%m-%d')
如果是DataFrame或Series的index,則轉換最核心的用法是:
pandas.DataFrame.index.strftime("%Y-%m-%d")
示例代碼
將series轉為字符串日期:
import pandas as pd
def convert_datetime(col_series: pd.Series):
? ? """series datetime64[ns] 轉 字符串日期"""
? ? if col_series.dtype == "datetime64[ns]":
? ? ? ? return col_series.dt.strftime('%Y-%m-%d')
? ? else:
? ? ? ? return col_series
def main():
? ? time_series = pd.Series(pd.date_range(start="20200101", periods=20, freq="D"))
? ? new_time_series = convert_datetime(time_series)
? ? print(time_series, "\n")
? ? print(new_time_series)
if __name__ == '__main__':
? ? main()
使用apply()將整個dataframe的所有datetime64[ns]都轉為object類型的日期數據
import pandas as pd
import numpy as np
def convert_datetime(col_series: pd.Series):
? ? """series datetime64[ns] 轉 字符串日期"""
? ? if col_series.dtype == "datetime64[ns]":
? ? ? ? return col_series.dt.strftime('%Y-%m-%d')
? ? else:
? ? ? ? return col_series
def main():
? ? time_df = pd.DataFrame(index=np.arange(0, 20))
? ? time_df['dt_col'] = pd.date_range(start="20200101", periods=20, freq="D")
? ? time_df['num_col'] = np.random.random(size=20)
? ? convert_time_df = time_df.apply(convert_datetime, axis=0)
? ? print(time_df.dtypes, "\n ==============")
? ? print(convert_time_df.dtypes)
if __name__ == '__main__':
? ? main()
python datetime與字符串、時間戳與字符串相互轉換
用flask處理前端傳過來的時間參數時,有可能是時間,也有可能是字符串,在不需要前端改動的情況下,后端可以自己處理。
情況1:將datetime形式轉為需要的字符串
(這樣的字符串在寫原生sql語句是可以當作實參傳遞使用)
import datetime
time1 = datetime.datetime.now()
print(type(time1))
print(time1)#假設前端傳的形式不符合后端要求
time1 = time1.strftime('%Y-%m-%d %H:%M:%S')#只取年月日,時分秒
print(type(time1))
print(time1)
情況2:將字符串形式的時間轉為datetime形式
import time,datetime
str_time = '2020-9-20 21:33:21'
fmt = '%Y-%m-%d %H:%M:%S'
print(str_time)
print(type(str_time))
str_time = datetime.datetime.strptime(str_time, "%Y-%m-%d %H:%M:%S")
print(str_time)
print(type(str_time))
情況3:約定前端傳過來datetime形式
形如2020-09-20 21:49:58.986521,我們已經將其處理成了字符串,我們只取前端傳過來的年月日,后面時分秒由自己添加,這時我們可以使用原生sql語句進行查詢,形如(只需要看懂傳字符串能查就行)
point_detect = db.session.execute("select a.id as flag_id,a.patrol_time,b.id as point_id,b.point_number,b.x_coor,b.y_coor from pipe_user_point a left join pipe_point b on a.pipe_point_id = b.id ?and a.pipe_user_id = '%s' and a.patrol_time <= '%s' and a.patrol_time >= '%s' and b.is_active = 1" % (patrol_id,start_time,end_time)).fetchall()
import time,datetime
start_time = datetime.datetime.now()
print(type(start_time))
print(start_time)#假設前端傳的形式不符合后端要求
start_time = start_time.strftime('%Y-%m-%d')#只取年月日 時分秒由自己添加
print(type(start_time))
print(start_time)
start_time = start_time + ' 00:00:00'
print(type(start_time))
print(start_time)
end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(type(end_time))
print(end_time)
情況4:對datetime形式的時間進行減操作
其中end_time會減去一天
import time,datetime
start_time = datetime.datetime.now()
print(type(start_time))
print(start_time)
end_time = datetime.datetime.now()
print(type(end_time))
print(end_time)
time = start_time - datetime.timedelta(days=1)#取一天之前
print(type(time))
print(time)
time = time.strftime('%Y-%m-%d %H:%M:%S')
print(type(time))
print(time)
21-7-7更新
情況5:將前端毫秒時間戳轉為年月日時分秒
def time_change_str(int_millisecond_time_stamp):
dateArray = datetime.datetime.fromtimestamp(int_millisecond_time_stamp / 1000)
otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
return otherStyleTime
#flask中的model.query.filter(model.report_time >= time1)可行
原文鏈接:https://blog.csdn.net/weixin_35757704/article/details/125598119
相關推薦
- 2023-02-09 Python如何提取html中文本到txt_python
- 2022-06-16 原生實現C#與Lua相互調用方法(Unity3D可用)_C#教程
- 2022-05-13 可變參C API va_list,va_start,va_arg_va_end以及c++可變參模板
- 2023-12-07 redis key
- 2022-09-21 Android開發Activity的生命周期詳解_Android
- 2022-04-04 webpack-plugins: plugin的使用 clean-webpack-plugin Cl
- 2022-02-18 連接redis服務器提示:Redis Client On Error: Error: connect
- 2022-09-08 go語言中函數與方法介紹_Golang
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支