简体   繁体   English

不支持的格式字符'm'

[英]unsupported format character 'm'

I am trying to convert now.month to decimal so it would look like 01 and not like 1. The code is: 我试图将now.month转换为十进制,所以它看起来像01而不是像1.代码是:

import datetime
now = datetime.datetime.now()
monthstr = ".%m" % now.month

it works in this line with %d 它与%d一起工作在这一行

daystr = "file_%d" % now.day

the error I get is 我得到的错误是

ValueError: unsupported format character 'm' (0x6d) at index 2 ValueError:索引2处不支持的格式字符'm'(0x6d)

I also tried with the new type {:%m}. 我也尝试使用新类型{:%m}。 The error is the same. 错误是一样的。 Do i miss any libraries? 我想念任何图书馆吗? Or is there another way except adding 0 to months from Jan to September 或者除了从1月到9月添加0到几个月之外还有其他方式

Python v.3.6.3 Python v.3.6.3

This is because %d do not stands for days . 这是因为%d不代表days It stands for digits and is a placeholder for numbers when using string formatting. 它代表数字,并且在使用字符串格式时是数字的占位符。

You should use it for months also. 您也应该使用它几个月。

monthstr = ".%d" % now.month

Since you want the format as 01 and not like 1 , use @user3483203 answer . 由于您希望格式为01 and not like 1 ,请使用@ user3483203 answer

You are using string formatting like datetime formatting here. 您正在使用字符串格式,如日期时间格式。 String formatting has its own "mini-language" , and m is not a valid symbol in this language. 字符串格式有自己的“迷你语言”m不是这种语言的有效符号。

For your purposes, it would be better to use strftime 为了您的目的,最好使用strftime

>>> now.strftime('.%m')
'.07'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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