简体   繁体   中英

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!

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM