问题:Python strftime-日期前无0?

使用Python时strftime,有一种方法可以删除日期的第一个0(如果它在10之前)。所以011?找不到%东西吗?

谢谢!

When using Python strftime, is there a way to remove the first 0 of the date if it’s before the 10th, ie. so 01 is 1? Can’t find a %thingy for that?

Thanks!


回答 0

实际上,我遇到了同样的问题,并且我意识到,如果在%和字母之间添加连字符,则可以删除前导零。

例如%Y/%-m/%-d

这仅适用于Unix(Linux,OS X),而不适用于Windows(包括Cygwin)。在Windows上,您可以使用#,例如%Y/%#m/%#d

Actually I had the same problem and I realized that, if you add a hyphen between the % and the letter, you can remove the leading zero.

For example %Y/%-m/%-d.

This only works on Unix (Linux, OS X), not Windows (including Cygwin). On Windows, you would use #, e.g. %Y/%#m/%#d.


回答 1

format从python2.6开始,随着方法的出现,我们可以做这种事情:

>>> import datetime
>>> '{dt.year}/{dt.month}/{dt.day}'.format(dt = datetime.datetime.now())
'2013/4/19'

尽管可能超出原始问题的范围,但是对于更有趣的格式,您可以执行以下操作:

>>> '{dt:%A} {dt:%B} {dt.day}, {dt.year}'.format(dt=datetime.datetime.now())
'Wednesday December 3, 2014'

从python3.6开始,这可以表示为嵌入式格式的字符串

Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dt = datetime.datetime.now()
>>> f'{dt:%A} {dt:%B} {dt.day}, {dt.year}'
'Monday August 29, 2016'

We can do this sort of thing with the advent of the format method since python2.6:

>>> import datetime
>>> '{dt.year}/{dt.month}/{dt.day}'.format(dt = datetime.datetime.now())
'2013/4/19'

Though perhaps beyond the scope of the original question, for more interesting formats, you can do stuff like:

>>> '{dt:%A} {dt:%B} {dt.day}, {dt.year}'.format(dt=datetime.datetime.now())
'Wednesday December 3, 2014'

And as of python3.6, this can be expressed as an inline formatted string:

Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dt = datetime.datetime.now()
>>> f'{dt:%A} {dt:%B} {dt.day}, {dt.year}'
'Monday August 29, 2016'

回答 2

%根据http://docs.python.org/library/time.html的介绍,某些平台可能支持字母之间的宽度和精度规范(例如月份中的“ d”),但这绝对是不可移植的解决方案(例如,在我的Mac上不起作用;-)。也许您可以在之后使用字符串替换(或RE,对于真正讨厌的格式)strftime进行补救?例如:

>>> y
(2009, 5, 7, 17, 17, 17, 3, 127, 1)
>>> time.strftime('%Y %m %d', y)
'2009 05 07'
>>> time.strftime('%Y %m %d', y).replace(' 0', ' ')
'2009 5 7'

Some platforms may support width and precision specification between % and the letter (such as ‘d’ for day of month), according to http://docs.python.org/library/time.html — but it’s definitely a non-portable solution (e.g. doesn’t work on my Mac;-). Maybe you can use a string replace (or RE, for really nasty format) after the strftime to remedy that? e.g.:

>>> y
(2009, 5, 7, 17, 17, 17, 3, 127, 1)
>>> time.strftime('%Y %m %d', y)
'2009 05 07'
>>> time.strftime('%Y %m %d', y).replace(' 0', ' ')
'2009 5 7'

回答 3

strftime()GNU C库支持的修饰符的文档。(就像之前说过的那样,它可能不是便携式的。)您可能感兴趣的是:

  • %e而不是%d将月份中的前导零替换为空格

它适用于我的Python(在Linux上)。我不知道它是否对您有用。

Here is the documentation of the modifiers supported by strftime() in the GNU C library. (Like people said before, it might not be portable.) Of interest to you might be:

  • %e instead of %d will replace leading zero in day of month with a space

It works on my Python (on Linux). I don’t know if it will work on yours.


回答 4

>>> import datetime
>>> d = datetime.datetime.now()
>>> d.strftime('X%d/X%m/%Y').replace('X0','X').replace('X','')
'5/5/2011'
>>> import datetime
>>> d = datetime.datetime.now()
>>> d.strftime('X%d/X%m/%Y').replace('X0','X').replace('X','')
'5/5/2011'

回答 5

在Windows上,添加一个’#’,例如’%#m /%#d /%Y%#I:%M:%S%p’

供参考:https : //msdn.microsoft.com/en-us/library/fe06s4ak.aspx

On Windows, add a ‘#’, as in ‘%#m/%#d/%Y %#I:%M:%S %p’

For reference: https://msdn.microsoft.com/en-us/library/fe06s4ak.aspx


回答 6

晚会很晚,但是%-d对我有帮助。

datetime.now().strftime('%B %-d, %Y')产生类似“ 2014年11月5日”的内容

欢呼:)

quite late to the party but %-d works on my end.

datetime.now().strftime('%B %-d, %Y') produces something like “November 5, 2014”

cheers :)


回答 7

我发现Django模板日期格式过滤器非常简单快捷。它去除了前导零。如果您不介意导入Django模块,请签出。

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date

from django.template.defaultfilters import date as django_date_filter
print django_date_filter(mydate, 'P, D M j, Y')    

I find the Django template date formatting filter to be quick and easy. It strips out leading zeros. If you don’t mind importing the Django module, check it out.

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date

from django.template.defaultfilters import date as django_date_filter
print django_date_filter(mydate, 'P, D M j, Y')    

回答 8

看一下-波纹管:

>>> from datetime import datetime
>>> datetime.now().strftime('%d-%b-%Y')
>>> '08-Oct-2011'
>>> datetime.now().strftime('%-d-%b-%Y')
>>> '8-Oct-2011'
>>> today = datetime.date.today()
>>> today.strftime('%d-%b-%Y')
>>> print(today)

Take a look at - bellow:

>>> from datetime import datetime
>>> datetime.now().strftime('%d-%b-%Y')
>>> '08-Oct-2011'
>>> datetime.now().strftime('%-d-%b-%Y')
>>> '8-Oct-2011'
>>> today = datetime.date.today()
>>> today.strftime('%d-%b-%Y')
>>> print(today)

回答 9

只需这样使用replace

(datetime.date.now()).strftime("%Y/%m/%d").replace("/0", "/")

它会输出:

'2017/7/21'

simply use replace like this:

(datetime.date.now()).strftime("%Y/%m/%d").replace("/0", "/")

it will output:

'2017/7/21'

回答 10

因为%d您可以使用转换为整数,int()否则它将自动删除前导0并变为整数。然后,您可以使用将其转换回字符串str()

For %d you can convert to integer using int() then it’ll automatically remove leading 0 and becomes integer. You can then convert back to string using str().


回答 11

例如,即使在同一OS的不同版本之间使用“%-d”也不是可移植的。更好的解决方案是分别提取日期成分,然后在日期特定的格式运算符和每个成分的日期属性访问之间进行选择。

e = datetime.date(2014, 1, 6)
"{date:%A} {date.day} {date:%B}{date.year}".format(date=e)

using, for example, “%-d” is not portable even between different versions of the same OS. A better solution would be to extract the date components individually, and choose between date specific formatting operators and date attribute access for each component.

e = datetime.date(2014, 1, 6)
"{date:%A} {date.day} {date:%B}{date.year}".format(date=e)

回答 12

因为Python实际上只是strftime(3)在您的平台上调用C语言函数,所以可能是有些格式字符可用于控制前导零;尝试man strftime看看。但是,当然,结果不会是可移植的,因为Python手册会提醒您。:-)

我会尝试使用一种新样式的datetime对象,该对象具有诸如t.yeart.month和的属性t.day,并通过%运算符的正常高效能格式来设置这些对象,该格式确实支持对前导零的控制。有关详细信息,请参见http://docs.python.org/library/datetime.html。更好的是,"".format()如果您的Python拥有运算符,并且更现代,请使用运算符。它也有许多数字格式选项。请参阅:http : //docs.python.org/library/string.html#string-formatting

Because Python really just calls the C language strftime(3) function on your platform, it might be that there are format characters you could use to control the leading zero; try man strftime and take a look. But, of course, the result will not be portable, as the Python manual will remind you. :-)

I would try using a new-style datetime object instead, which has attributes like t.year and t.month and t.day, and put those through the normal, high-powered formatting of the % operator, which does support control of leading zeros. See http://docs.python.org/library/datetime.html for details. Better yet, use the "".format() operator if your Python has it and be even more modern; it has lots of format options for numbers as well. See: http://docs.python.org/library/string.html#string-formatting.


回答 13

基于Alex的方法,这将适用于字符串开头和空格后的情况:

re.sub('^0|(?<= )0', '', "01 January 2000 08:00am")

我喜欢它比.format或%-d好,因为它是跨平台的,可以让我继续使用strftime(获取“ 11月”和“星期一”之类的信息)。

Based on Alex’s method, this will work for both the start-of-string and after-spaces cases:

re.sub('^0|(?<= )0', '', "01 January 2000 08:00am")

I like this better than .format or %-d because this is cross-platform and allows me to keep using strftime (to get things like “November” and “Monday”).


回答 14

老问题了,但是%l(小写L)在strftime中对我有用:但是,这可能不适用于每个人,因为我发现的Python文档中未列出

Old question, but %l (lower-case L) worked for me in strftime: this may not work for everyone, though, as it’s not listed in the Python documentation I found


回答 15

import datetime
now = datetime.datetime.now()
print now.strftime("%b %_d")
import datetime
now = datetime.datetime.now()
print now.strftime("%b %_d")

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。