Python newb here. I have a string as 'July 27, 2019' I want output as 'Jul. 27, 2019' Please let me know how can I achieve the same.
Asked
Active
Viewed 45 times
-7
-
use replace function in strings. – vishal Jul 27 '18 at 13:27
-
3Consider this `datetime.datetime.strptime(date_string, format1).strftime(format2)` – scharette Jul 27 '18 at 13:28
-
[`strftime()` and `strptime()`](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior) – Jul 27 '18 at 13:29
-
1Also, guys stop down voting him, he is obviously new... Instead let's explain to him what he should do in the future. – scharette Jul 27 '18 at 13:30
-
1Welcome to SO. Please take the time to read [ask] and the other links found on that page. – wwii Jul 27 '18 at 13:31
-
Well, that's what [these links](http://idownvotedbecau.se/noresearch/) are for. I downvoted because there's no research, no code, and only a statement of "I need X." – Jul 27 '18 at 13:32
-
@JoshDetwiler Down-voting him is entirely justifed since you at least provided him with a reason, that's what I meant. – scharette Jul 27 '18 at 13:33
-
2Possible duplicate of [Parse date string and change format](https://stackoverflow.com/questions/2265357/parse-date-string-and-change-format) – scharette Jul 27 '18 at 13:34
1 Answers
2
Use the datetime
module.
Ex:
import datetime
d = 'July 27, 2019'
print( datetime.datetime.strptime(d, "%B %d, %Y").strftime("%b. %d, %Y") )
Output:
Jul. 27, 2019
strptime
to convert string to datetime object.strftime
to convert the datetime object to your required format.

Rakesh
- 81,458
- 17
- 76
- 113
-
Hi @Rakesh, Thanks for above answer. If my d = 'Aug. 27, 2019', then also above logic will work?? Or it will not work?? Please let me know Sometimes month is displayed as "July" or sometimes as "Aug." I want output as "First 3 chars of month followed by a dot" E.g. October 27, 2019 will be shown as "Oct. 27, 2019" i.e. whenever month name length exceeds 3, it should be reduced to 3 and followed by a dot. – Monish Correia Jul 30 '18 at 07:34