Skip to content

Instantly share code, notes, and snippets.

@navinthenapster
Created May 8, 2019 11:56
Show Gist options
  • Save navinthenapster/6d260357b2f4b491ea7fd5b95c0b55a9 to your computer and use it in GitHub Desktop.
Save navinthenapster/6d260357b2f4b491ea7fd5b95c0b55a9 to your computer and use it in GitHub Desktop.
Date Format utils function Included the regular expression and the datetime utils function.
import re
from datetime import datetime, timedelta
datas=["01:48PM","Yesterday 06:31PM", "04/08 05:25PM","11/07/2018 05:12PM"]
def date_parse(data):
pattern1 = "(\d{2}):(\d{2})([AaPp][Mm])"
pattern2 = "Yesterday "+pattern1
pattern3 = "(\d{2})/(\d{2}) "+pattern1
pattern4 = "(\d{2})/(\d{2})/(\d{4}) " +pattern1
actual_date=datetime.today()
# pattern_test=pattern1
# print re.match(pattern_test,datas[0])
# print re.match(pattern_test,datas[1])
# print re.match(pattern_test,datas[2])
# print re.match(pattern_test,datas[3])
if re.match(pattern1,data):
m=re.match(pattern1,data)
hh,mm,mode=int(m.group(1)),int(m.group(2)),m.group(3)
if mode == "PM": hh+=12
if hh >=24 : hh=hh-24
actual_date = actual_date.replace(hour=hh, minute=mm)
elif re.match(pattern2,data):
m=re.match(pattern2,data)
hh,mm,mode=int(m.group(1)),int(m.group(2)),m.group(3)
if mode == "PM": hh+=12
if hh >=24 : hh=hh-24
actual_date = actual_date.replace(hour=hh, minute=mm) - timedelta(days=1)
elif re.match(pattern3,data):
m=re.match(pattern3,data)
DD,MM,hh,mm,mode=int(m.group(1)),int(m.group(2)),int(m.group(3)),int(m.group(4)),m.group(5)
if mode == "PM": hh+=12
if hh >=24 : hh=hh-24
actual_date = actual_date.replace(day=DD , month=MM, hour=hh, minute=mm)
elif re.match(pattern4,data):
m=re.match(pattern4,data)
DD,MM,YYYY,hh,mm,mode=int(m.group(1)),int(m.group(2)),int(m.group(3)),int(m.group(4)),int(m.group(5)),m.group(6)
if mode == "PM": hh+=12
if hh >=24 : hh=hh-24
actual_date = actual_date.replace(day=DD , month=MM,year=YYYY,hour=hh, minute=mm)
actual_date=actual_date.replace(second=00,microsecond=00)
return actual_date
# for data in datas:
# print date_parse(data)
current_date=datetime.today()
date_format=current_date.strftime("%a %m/%d/%Y")
print date_format
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment