date
is in this format %Y-%m-%d %H:%M:%S
[this is 24 hours].I want to convert this date in 12 hours something like this -> %Y-%m-%d %H:%M:%S %p
and vice-versa
.
How can i achieve this?? Thanx!
Asked
Active
Viewed 6,645 times
1

Pranay
- 45
- 1
- 5
-
Presumably you have string input and want string output? Have you tried anything yourself yet, you *already* have string formats there. – Martijn Pieters Apr 28 '16 at 11:49
-
`datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %I:%M:%S %p')` – Burhan Khalid Apr 28 '16 at 11:52
2 Answers
3
Load the string into a datetime object via strptime()
, then dump via strftime()
in the desired format:
>>> from datetime import datetime
>>> d = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
>>> d # d is a string
'2016-04-28 07:46:32'
>>> datetime.strptime(d, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %I:%M:%S %p")
'2016-04-28 07:46:32 AM'
Note that the %I
here is a 12-hour clock.

alecxe
- 462,703
- 120
- 1,088
- 1,195
-
Thank you ! @alecxe..and vice-versa..I mean again wanted to 24 of 12 hours then??? – Pranay Apr 28 '16 at 11:52
-
@Pranay make the same procedure, but now `strptime` using `%Y-%m-%d %I:%M:%S %p` and `strftime` using `%Y-%m-%d %H:%M:%S`. – alecxe Apr 28 '16 at 11:53
2
24 hour to 12-hour
>>> from datetime import datetime
>>> datetime.strptime('2016-05-25 13:45:56', '%Y-%m-%d %H:%M:%S')
datetime.datetime(2016, 5, 25, 13, 45, 56)
>>> dt=datetime.strptime('2016-05-25 13:45:56', '%Y-%m-%d %H:%M:%S')
>>> dt.strftime('%Y-%m-%d %I:%M:%S %p')
'2016-05-25 01:45:56 PM'
>>>
12-hour to 24-hour
>>> dt=datetime.strptime('2016-05-25 01:45:56 PM', '%Y-%m-%d %I:%M:%S %p')
>>> dt
datetime.datetime(2016, 5, 25, 13, 45, 56)
>>> dt.strftime('%Y-%m-%d %H:%M:%S')
'2016-05-25 13:45:56'
>>>

riteshtch
- 8,629
- 4
- 25
- 38
-
-
@chanchalpardeshi you could use something like this `dt=datetime.strptime('12:00 AM', '%I:%M %p')` and then `dt.strftime('%H:%M:%S')` which will print `'00:00:00'` – riteshtch May 27 '17 at 04:06
-