Python Forum
replace and extract value - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: replace and extract value (/thread-38323.html)



replace and extract value - mg24 - Sep-28-2022

Hi Team,

I have below input variables.

market date 6 digit exclude dashes.
RunTime = all digit except last 3, remove "-", " " , ":"

Input variable
Market_date = '2022-04-22 00:00:00:000'
RunTime = '2022-04-20 16:20:28:000'
Expected output
Market_date = "20220422"
RunTime = "20220420162028"



RE: replace and extract value - carecavoador - Sep-28-2022

It is possible to do it using datetime and f-strings:

from datetime import datetime

Market_date = '2022-04-22 00:00:00:000'
RunTime = '2022-04-20 16:20:28:000'

Market_date = datetime.fromisoformat(Market_date)
RunTime = datetime.fromisoformat(RunTime)

print(f'{Market_date:%Y%m%d}')
print(f'{RunTime:%Y%m%d%H%M%S}')



RE: replace and extract value - Larz60+ - Sep-28-2022

try:
from datetime import datetime

Market_date = '2022-04-22 00:00:00:000'
RunTime = '2022-04-20 16:20:28:000'

format = '%Y-%m-%d %H:%M:%S'

date = datetime.strptime(Market_date[:19], format)
rtime = datetime.strptime(RunTime[:19], format)

new_Market_date = f"{date.year}{date.month}{date.day}"
new_RunTime = f"{rtime.year}{rtime.month}{rtime.day}{rtime.hour}{rtime.minute}{rtime.second}"

print(f"new_Market_date: {new_Market_date}")
print(f"new_RunTime: {new_RunTime}")
Output:
new_Market_date: 2022422 new_RunTime: 2022420162028



RE: replace and extract value - mg24 - Oct-11-2022

Hi Team,

code is working,

but I want output in two digit for dd and mm.
I am extracting data from sql table. converted to string ,

dart\month
1 ---- will be 01
2 ---- will be 02

10 will be 10 etc.

TypeError: fromIsoformat: Argument must of str.
if when trying in actual code.


RE: replace and extract value - rob101 - Oct-11-2022

Does this work for you?

new_Market_date = f"{date.year}{date.month:02d}{date.day:02d}"



RE: replace and extract value - deanhystad - Oct-11-2022

datatime has a function for converting strings to datetime objects (strptime). It also has a function for converting datetime objects to strings (strftime).

You can read about the functions and the datetime format codes here:

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes.

There is a format codes for zero padded month and zero padded day.