Pranay
Pranay

Reputation: 45

Conversion of 24 hours date/time to 12 hours format and vice-versa

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!

Upvotes: 1

Views: 6978

Answers (2)

riteshtch
riteshtch

Reputation: 8769

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'
>>> 

Upvotes: 2

alecxe
alecxe

Reputation: 473863

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.

Upvotes: 3

Related Questions