简体   繁体   中英

How to format “dd/mm/yyyy” of string type to “yyyy-mm-dd” enclosed in single quotes in python?

Problem Statement: assign the date (where there is maximum pressure difference) in string format as 'yyyy-mm-dd'. Make sure you enclose it with single quote.

test.py file is provided with the question for checking my notebook. Its read only and I am not allowed to edit it.

test.py

import re
from hashlib import md5
import nbformat
import pickle

def read_ipynb_file(file_path):
    with open(file_path) as file:
        out = str(nbformat.read(file_path, as_version=4))
    return out

path = 'question/EDA_question.ipynb'

out = read_ipynb_file(path)


max_p_range_day =  re.findall(r'max_p_range_day\s*=\s*\'\d*[-,]?\d*[-,]?\d*\'', out)[0].replace(' ', '').replace(' ', '').replace("'", "") 

Error:

___________________________ ERROR collecting test.py ___________________________

test.py:23: in <module>

    max_p_range_day =  re.findall(r'max_p_range_day\s*=\s*\'\d*[-,]?\d*[-,]?\d*\'', out)[0].replace(' ', '').replace("'", "")

E   IndexError: list index out of range

In dataset "Day" column has dates which are type strings like this: "23/03/2018".

My code:

....
df5=pd.to_datetime(df5['Day']).dt.date  # date which has maximum pressure diff   

from datetime import datetime
max_p_range_day = datetime.strftime(df5.values[0],"'%Y-%m-%d'")

This is printing the date in single quotes but shows error when test.py evaluates it.

For checking myself, I tried this:

  1. wrote max_p_range_day in file -

Content of file:

max_p_range_day = '2018-03-23'
  1. Then did this:

    x=open("handson_date.txt",'r')

    out=x.read()

    res=re.findall(r'max_p_range_day\s*=\s*\'\d*[-,]?\d*[-,]?\d*'', out)[0].replace(' ', '').replace("'", "")

There was no error. res showed 'max_p_range_day=2018-03-23'.

But when my code is tested using test.py the error is thrown.

Kindly suggest how to address this concern.

Change your code with below

re.findall(r"max_p_range_day\s*=\s*'\d*[-]\d*[-]\d*'",out)[0].replace(' ', '').replace("'", "")

This will work with you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM