Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
replace and extract value
#1
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"
Reply
#2
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}')
Reply
#3
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
Reply
#4
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.
Reply
#5
Does this work for you?

new_Market_date = f"{date.year}{date.month:02d}{date.day:02d}"
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#6
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/dateti...rmat-codes.

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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Search & Replace - Newlines Added After Replace dj99 3 3,394 Jul-22-2018, 01:42 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020