pandas如何将datetime64[ns]转为字符串日期

 更新时间:2022年07月12日 10:40:29   作者:呆萌的代Ma  
这篇文章主要介绍了pandas如何将datetime64[ns]转为字符串日期,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

将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)可行

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。 

相关文章

  • 深入浅析Python获取对象信息的函数type()、isinstance()、dir()

    深入浅析Python获取对象信息的函数type()、isinstance()、dir()

    这篇文章主要介绍了Python获取对象信息的函数type()、isinstance()、dir()的相关知识,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2018-09-09
  • 基于Python绘制三种不同的中国结

    基于Python绘制三种不同的中国结

    马上就要迎来新年了,就绘制了几个中国结,嘿嘿!本文为大家整理了三个绘制中国结的方法,文中的示例代码讲解详细,快跟随小编一起动手尝试一下吧
    2023-01-01
  • python字符串操作详析

    python字符串操作详析

    这篇文章主要介绍了python字符串操作,字符串是不可变类型可以重新赋值,但不可以索引改变其中一个值,只能拼接字符串建立新变量,下面来了解具体内容吧,需要的小伙伴可以参考一下
    2022-02-02
  • python实现移动木板小游戏

    python实现移动木板小游戏

    这篇文章主要为大家详细介绍了python实现移动木板小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-10-10
  • python忽略警告(warning)的3种方法小结

    python忽略警告(warning)的3种方法小结

    python开发中经常遇到报错的情况,但是warning通常并不影响程序的运行,而且有时特别讨厌,下面我们来说下如何忽略warning错误,这篇文章主要给大家介绍了关于python忽略警告(warning)的3种方法,需要的朋友可以参考下
    2023-10-10
  • Python如何实现转换URL详解

    Python如何实现转换URL详解

    这篇文章主要介绍了Python如何实现转换URL详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-07-07
  • 解决pycharm不能自动补全第三方库的函数和属性问题

    解决pycharm不能自动补全第三方库的函数和属性问题

    这篇文章主要介绍了解决pycharm不能自动补全第三方库的函数和属性问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-03-03
  • Python实现文件内容批量追加的方法示例

    Python实现文件内容批量追加的方法示例

    这篇文章主要介绍了Python实现文件内容批量追加的方法,结合实例形式分析了Python文件的读写相关操作技巧,需要的朋友可以参考下
    2017-08-08
  • 一篇文章教会你PYcharm的用法

    一篇文章教会你PYcharm的用法

    这篇文章主要介绍了Pycharm新手使用教程(图文详解),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-08-08
  • Python中的协程(Coroutine)操作模块(greenlet、gevent)

    Python中的协程(Coroutine)操作模块(greenlet、gevent)

    这篇文章介绍了Python中的协程(Coroutine)操作模块(greenlet、gevent),文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-05-05

最新评论