How can I convert "dd/MM/yyyy"
, "HH:mm"
, "dd-MMM-yy"
, "M/d/yyyy"
etc., to "%d/%m/%Y"
, "%H:%M"
, "%d-%b-%y"
or "%m/%d/%Y"
etc?
Asked
Active
Viewed 5,595 times
2

Bleeding Fingers
- 6,993
- 7
- 46
- 74
-
Interesting, but do you want this to work for any valid `datetime` ? – jamylak May 24 '13 at 12:39
-
@jamylak I didn't understand your question. Any example of an invalid `datetime`? – Bleeding Fingers May 24 '13 at 12:43
-
I'm asking if you want to support the whole table here: http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior – jamylak May 24 '13 at 12:44
-
@jamylak not the whole table, just those which have equivalent user understandable representations. And while I am at it, what would be the equivalent of `"%j"`? – Bleeding Fingers May 24 '13 at 12:50
-
`ddd` is what you mean?? – jamylak May 24 '13 at 12:55
-
@jamylak yup. Didn't know about that. – Bleeding Fingers May 24 '13 at 13:07
-
The input format looks like ICU date format; you could [pass it to `icu.SimpleDateFormat`, to parse a date string](http://stackoverflow.com/a/29548727/4279) – jfs May 09 '15 at 10:44
-
@J.F.Sebastian I wanted to convert, e.g., the actual "dd/mm/yyyy" to "%d/%m/%Y" not "09/05/2015". – Bleeding Fingers May 09 '15 at 16:47
-
@BleedingFingers: I understand it that is why I've posted a *comment*, not an *answer*. You could use ICU API *instead of* strptime-based API. – jfs May 09 '15 at 16:52
2 Answers
2
You may extend replacements
to cover all possible user date time formats (you may also edit this answer to include them here)
import re
replacements = {
r'dd': '%d',
r'd': '%d',
r'MM': '%m',
r'M': '%m',
r'yyyy': '%Y',
r'HH': '%H',
r'mm': '%M',
r'MMM': '%b',
r'yy': '%Y',
}
def fn(match):
return replacements[match.group()]
def F(text):
pat = '|'.join(r'\b' + re.escape(k) + r'\b' for k in replacements)
return re.sub(pat, fn, text)
>>> F("dd/MM/yyyy")
'%d/%m/%Y'
>>> F("HH:mm")
'%H:%M'
>>> F("dd-MMM-yy")
'%d-%b-%Y'
>>> F("M/d/yyyy")
'%m/%d/%Y'

jamylak
- 128,818
- 30
- 231
- 230
0
change the format of date time
import datetime
d = datetime.datetime.strptime("2013-05-24", "%Y-%m-%d") datetime.datetime(2013, 5, 24, 0, 0)
d.format("%d.%b.%Y") '24-May-2013'
The format function in put before and after two underscore

Naresh Chaudhary
- 705
- 5
- 14