简体   繁体   中英

How to format date in single quoted string “yyyy-mm-dd” in python?

How to format date in single quoted string "yyyy-mm-dd" in python that matches the following regex?

r'max_p_range_day\s*=\s*\'\d*[-,]?\d*[-,]?\d*\''

The code:

pmax=df5.iloc[:,-5]  # maximum pressure
pmin=df5.iloc[:,-4]   # minimum pressure

df5['PressureDiff']=pmax-pmin
pm=df5["PressureDiff"].max()
df5=df5.loc[df5.PressureDiff==pm]
df5=pd.to_datetime(df5['Day']).dt.date   

from datetime import datetime
max_p_range_day = ## format as yyyy-mm-dd enclosed in single quotes
t=open("handson_date.txt",'w')
t.write("max_p_range_day = %s" % max_p_range_day)

For testing the file where I wrote my answer, code is as follows:

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("'", "")

How to format the date to match the following regex?

To format datetime you have strftime()

For today date

 datetime.datetime.now().strftime("'%Y-%m-%d'")

Result (and ' ' is part of result)

'2021-01-08' 

You can even use it with other text

datetime.datetime.now().strftime("max_p_range_day = '%Y-%m-%d'")

Result

max_p_range_day = '2021-01-08'

And the same you can do even in DataFrame

import datetime
import pandas as pd

one_day = datetime.timedelta(days=1)
today = datetime.datetime.today()

df = pd.DataFrame({'date': [today, today-one_day, today+one_day]})
print(df)


result = df['date'].dt.strftime("max_p_range_day = '%Y-%m-%d'")
print(result)

Result

                        date
0 2021-01-08 10:12:51.295168
1 2021-01-07 10:12:51.295168
2 2021-01-09 10:12:51.295168


0    max_p_range_day = '2021-01-08'
1    max_p_range_day = '2021-01-07'
2    max_p_range_day = '2021-01-09'
Name: date, dtype: object

EDIT: You have to add ' ' around %s in "max_p_range_day = '%s'"

from datetime import datetime
import re

max_p_range_day = datetime.today().strftime("%Y-%m-%d")   # <-- without `' '`
print('data:', max_p_range_day)

t = open('handson_date.txt', 'w')
t.write("max_p_range_day = '%s'" % max_p_range_day)  # <-- add `' '`
t.close()   # need it to correctly save all data

# ---------------------

x = open('handson_date.txt')
out = x.read()

print('out:', out)

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

if res:
    res = res[0].replace(' ', '').replace("'", "")
    print('found:', res)
else:
    print('?')

Or you have to use ' ' in strftime("'%Y-%m-%d'")

from datetime import datetime
import re

max_p_range_day = datetime.today().strftime("'%Y-%m-%d'")  # <-- add `' '`

print('data:', max_p_range_day)

t = open('handson_date.txt', 'w')
t.write("max_p_range_day = %s" % max_p_range_day)  # <-- without `' '`
t.close()   # need it to correctly save all data

# ---------------------

x = open('handson_date.txt')
out = x.read()

print('out:', out)

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

if res:
    res = res[0].replace(' ', '').replace("'", "")
    print('found:', res)
else:
    print('?')

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