【问题标题】:How to create datetime index from string in python?如何从python中的字符串创建日期时间索引?
【发布时间】:2019-10-20 15:32:36
【问题描述】:

共有三个文件名:file_2018-01-01_01_temp.tiffile_2018-01-01_02_temp.tiffile_2018-01-01_03_temp.tif。我想在 python 中将它们的名称列为['2018010101', '2018010102', '2018010103']。 下面的代码创建了一个不正确的列表。

import pandas as pd
from glob import glob
from os import path

pattern = '*.tif'
filenames = [path.basename(x) for x in glob(pattern)]
pd.DatetimeIndex([pd.Timestamp(f[5:9]) for f in filenames])

结果: DatetimeIndex(['2018-01-01', '2018-01-01', '2018-01-01']

【问题讨论】:

    标签: python-3.x string pandas datetime


    【解决方案1】:

    我认为最简单的方法是在列表理解中使用替换进行索引:

    a = [f[5:18].replace('_','').replace('-','') for f in filenames]
    print (a)
    ['2018010101', '2018010102', '2018010103']
    

    Series.str.replace类似:

    a = pd.Index([f[5:18] for f in filenames]).str.replace('\-|_', '')
    print (a)
    Index(['2018010101', '2018010102', '2018010103'], dtype='object')
    

    或者将值转换为DatetimeIndex,然后使用DatetimeIndex.strftime

    a = pd.to_datetime([f[5:18] for f in filenames], format='%Y-%m-%d_%H').strftime('%Y%m%d%H')
    print (a)
    Index(['2018010101', '2018010102', '2018010103'], dtype='object')
    

    编辑:

    dtype 在 object 中,但必须在 dtype='datetime64[ns]

    如果需要日期时间,那么格式必须是默认的,不能改变它:

    d = pd.to_datetime([f[5:18] for f in filenames], format='%Y-%m-%d_%H')
    print (d)
    DatetimeIndex(['2018-01-01 01:00:00', '2018-01-01 02:00:00',
                   '2018-01-01 03:00:00'],
                  dtype='datetime64[ns]', freq=None)
    

    【讨论】:

    • 嗨@jezrael,dtype 在object,但它必须在dtype='datetime64[ns]
    猜你喜欢
    • 2017-08-13
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    相关资源
    最近更新 更多