【问题标题】:how to avoid pandas in converting string to date format如何避免熊猫将字符串转换为日期格式
【发布时间】:2020-03-11 14:06:48
【问题描述】:

我有下面的代码,它检查日期是否在开始日期和结束日期之间并返回其文件名。

import pandas as pd
def loaddata():

global dict1
dict1 = {}

with open('load.csv', mode='r') as f:
    for z in csv.DictReader(f, skipinitialspace=True):
        Start_date = pd.to_datetime(z['Start_date'])
        End_date = pd.to_datetime(z['End_date'])
        File_type = z['File_type']
        File_name = z['File_name']

        if File_name not in dict1:
            dict1[File_name] = {}
        if File_type not in dict1[File_name]:
            dict1[File_name][File_type] = (Start_date, End_date)

# dict1 gives  >> {'file_name': {'type1': (Timestamp('2019-05-06 00:00:00'), Timestamp('2019-12-31 00:00:00'))},
# 'file_name1': {'type2': (Timestamp('2018-05-06 00:00:00'), Timestamp('2018-12-31 00:00:00'))}}

def fn(date, filetype):
    for filename, range in dict1.items():
        if filetype in range:
            start, end = range[filetype]
            if start <= date <= end:
                return filename


new_date = pd.to_datetime('2019-12-21')
print(fn(new_date, 'type1'))   
# >> returns filename

我使用 pandas 将字符串日期转换为日期格式。 没有熊猫有什么办法可以转换吗?

【问题讨论】:

    标签: python django pandas


    【解决方案1】:

    当然是的:

    from datetime import datetime
    
    date_string = "2017/01/31"
    
    date = datetime.strptime(date_string, "%Y/%m/%d")
    
    print(date)
    # datetime.datetime(2017, 1, 31, 0, 0)
    
    

    【讨论】:

    • 另外看看 dateutil,whixh 是 datetime 的扩展。
    • @WwatlawW 是的。我知道dateutil,但我想保持简单。
    • 我尝试了Start_date = datetime.datetime.strptime(row['Start_date'], "%m/%d/%Y") 并得到if start &lt;= date &lt;= end: TypeError: can't compare datetime.datetime to datetime.date 错误
    • 您的一个日期是datetime.date 对象,这不一样。这个link 会有所帮助。检查您的startdateend 是如何定义的。您现在可以编辑您的问题以包含较新的行
    • 也许我不应该作为评论添加,我是为其他人添加的。
    猜你喜欢
    • 2020-08-02
    • 2018-05-26
    • 2017-09-17
    • 2017-05-20
    • 2021-07-28
    • 2016-03-24
    • 2014-02-23
    • 1970-01-01
    相关资源
    最近更新 更多