I want to convert 22-Jul-2020 14:00 (GMT 4.30)
to 22 7 2020
in order
to insert it into my database.
Your help is much appreciated.
I want to convert 22-Jul-2020 14:00 (GMT 4.30)
to 22 7 2020
in order
to insert it into my database.
Your help is much appreciated.
You want to use strftime() and strptime()
strptime
is used to change your date string into a datetime
format. strftime
then turns it back into another formatted string, presuming that is what you wish to do.
from datetime import datetime
s = '22-Jul-2020 14:00 (GMT 4.30)'
dt = datetime.strptime(s, '%d-%b-%Y %H:%M (%Z 4.30)')
out = dt.strftime('%d %m %Y')
print(out)
Returns
22 07 2020
One problem is that strptime
will struggle with the way the offset (GMT 4.30) is formatted at the end. Since the term 'GMT' is all you should need to retrieve the timezone, I suggest stripping the rest out using regex - if the timezone matters to you.
import re
from datetime import datetime
s = '22-Jul-2020 14:00 (GMT 4.30)'
s_stripped = re.sub('\(([A-Z]+).+\)', r'\1', s)
# s_stripped is '22-Jul-2020 14:00 GMT'
dt = datetime.strptime(s_stripped, '%d-%b-%Y %H:%M %Z')
out = dt.strftime('%d %m %Y')
print(out)
If you want to keep only the date part from the string, you can use this:
from datetime import datetime
s = "22-Jul-2020 14:00 (GMT 4.30)"
d = datetime.strptime(s.split()[0], "%d-%b-%Y")
desired_output = '{d.day} {d.month} {d.year}'.format(d=d)
print(desired_output)
x = datetime.strftime(d, "%d %m %Y")
print(x)
Output:
22 7 2020
22 07 2020
After creating the datetime
object from the string, I have shown both string formatting and strftime
to convert the datetime
to required format. As you can see the strftime
returns a zero padded month which is not required for your case.
Reference:
You can use Regex to accomplish, but I would like to use in this case replace()
method, it will replace the something to something like below:
date = "22-Jul-2020 14:00"
newDate = date.replace("-", " ")[:11]
print(newDate)
Output:
22 Jul 2020
learn more about Replace()
Happy Codin`!