将24小时日期/时间转换为12小时格式,反之亦然 [英] Conversion of 24 hours date/time to 12 hours format and vice-versa

查看:98
本文介绍了将24小时日期/时间转换为12小时格式,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

日期的格式为%Y-%m-%d%H:%M:%S [这是24小时]。我想在12小时内将此日期转换为类似的结果-> %Y-%m-%d%H:%M:%S%p
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!

推荐答案

通过 strptime() ,然后通过 strftime() 所需的格式:

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'

请注意%I 这是一个 12小时制

这篇关于将24小时日期/时间转换为12小时格式,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆