如何避免将字符串转换为日期格式的 pandas [英] how to avoid pandas in converting string to date format

查看:65
本文介绍了如何避免将字符串转换为日期格式的 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have below code where it checks if the date is in between start and end dates and returns its filename.

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

我用熊猫将字符串日期转换为日期格式.有没有办法在没有熊猫的情况下进行转换?

I used pandas for converting the string dates to date format. Is there any way to convert it without pandas ?

推荐答案

当然可以:

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)

这篇关于如何避免将字符串转换为日期格式的 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆