python - 将时间格式化为 %d-%m-%y

标签 python

我试图将 orig_time 打印为 6/9/2013 并遇到以下错误..任何人都可以提供有关此处错误的信息

代码:

orig_time="2013-06-09 00:00:00"
Time=(orig_time.strftime('%m-%d-%Y'))
print Time

错误:-

Traceback (most recent call last):
  File "date.py", line 2, in <module>
    Time=(orig_time.strftime('%m-%d-%Y'))
AttributeError: 'str' object has no attribute 'strftime'

最佳答案

您不能在字符串上使用 strftime,因为它不是字符串的方法,一种方法是使用 datetime模块:

>>> from datetime import datetime
>>> orig_time="2013-06-09 00:00:00"
#d is a datetime object    
>>> d = datetime.strptime(orig_time, '%Y-%m-%d %H:%M:%S')

现在您可以使用任一字符串格式:

>>> "{}/{}/{}".format(d.month,d.day,d.year)
'6/9/2013'

datetime.datetime.strftime :

>>> d.strftime('%m-%d-%Y')
'06-09-2013'

关于python - 将时间格式化为 %d-%m-%y,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17245612/

相关文章:

python - Django CBV - 如何避免为每个 View 重复 get_context_data 以获得自定义标题?

python - 为什么这个来自 python 的 bash 调用不起作用?

python - 列表中删除、删除和弹出的区别

python - 在 Qt 的槽中使用任何 'return' 语句会产生什么影响

python - 我继承的类 MenuBar(tk.Menu) 不显示菜单栏

python - 如果 Y 有 NaN 使用 python 将数据从列 X 填充到列 Y

python - openCV:无法使用 findContours 检测小形状

python - 在提交对象之前从 SqlAlchemy 获取主键

python - 用 tcl 编写的 irc bot 与 python/node.js 克隆相比如何?

python - 从 pygame 中的二维列表渲染背景框类时出现问题