2016-12-04 48 views
0
import datetime 

date = datetime.datetime.now() 
result = True 
phoneNum ="(111)111-1111" 
Message = "Hey !" 
tmp = "{0:10s}{1:}{2:}{3:10s}".format(phoneNum, date,result, Message) 

我应该使用什么格式为datetime.datetime和布尔一样,我们会用“S”为字符串和“d”为整数 以及如何打印为12月3日的日期格式年,2016年8:00 PM如何打印布尔型和datetime.datetime类型的格式化报告?

+0

大多数类实现一个表示该对象为字符串一个'__str__'方法。对于日期时间,您需要分别指定日期格式。你应该使用'strftime'来打印时间。 –

回答

1

我发现最容易打印这种方式,使用大括号与.format()方法中参数的索引。不需要在字符串中指定数据类型,并且如果只有1个参数,则不需要数字索引。

有关日期格式的详细信息请参阅本link

import datetime 

date = datetime.datetime.now().strftime('%b %d, %Y %I:%M%p') 
result = True 
phoneNum ="(111)111-1111" 
Message = "Hey !" 
tmp = "phone: {0}\ndate: {1}\nresult: {2}\nMessage: {3}".format(phoneNum, date, result, Message) 

print(tmp) 

variable = 'Variable printed without specifying an index' 

print('\nstring: {}'.format(variable)) 

输出:

phone: (111)111-1111 
date: Dec 6, 2016 07:00PM 
result: True 
Message: Hey ! 

string: Variable printed without specifying an index 
+0

我想你想在日期格式的日期部分使用'%d'而不是'%w'。 '%w'会以数字形式给你一周中的一天 – lemonhead

+0

正确,谢谢柠檬头。我做了改变。 –