Python strftime - 不带前导0的日期?

发布于 2024-07-20 12:48:27 字数 146 浏览 8 评论 0 原文

当使用Python strftime时,如果日期在10号之前,有没有办法删除日期的前0,即。 那么 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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(22

×眷恋的温暖 2024-07-27 12:48:28

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

我会尝试使用新型 datetime 对象,它具有诸如 t.yeart.month 等属性>t.day,并将它们置于 % 运算符的正常、高性能格式化中,该运算符确实支持对前导零的控制。 有关详细信息,请参阅 http://docs.python.org/library/datetime.html 。 更好的是,如果您的 Python 有 "".format() 运算符,那么它会更现代; 它还有很多数字格式选项。 请参阅: http://docs.python.org/library/string.html#字符串格式

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.

折戟 2024-07-27 12:48:28

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

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

我比 .format 或 %-d 更喜欢这个,因为这是跨平台的,并且允许我继续使用 strftime (来获取内容)例如“十一月”和“星期一”)。

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").

梦途 2024-07-27 12:48:28

老问题,但是 %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

无人接听 2024-07-27 12:48:28
import datetime
now = datetime.datetime.now()
print now.strftime("%b %_d")
import datetime
now = datetime.datetime.now()
print now.strftime("%b %_d")
城歌 2024-07-27 12:48:28

我迟到了,但是一个简单的列表切片就可以完成工作

today_date = date.today().strftime('%d %b %Y')
if today_date[0] == '0':
    today_date = today_date[1:]

I am late, but a simple list slicing will do the work

today_date = date.today().strftime('%d %b %Y')
if today_date[0] == '0':
    today_date = today_date[1:]
烟火散人牵绊 2024-07-27 12:48:28

标准库对于大多数情况来说已经足够好了,但是对于真正详细的日期操作,您应该始终寻找一些专门的第三方库。

使用箭头

>>> import arrow
>>> arrow.utcnow().format('dddd, D. M. YYYY')
'Friday, 6. 5. 2022'

查看完整的支持的令牌列表

The standard library is good enough for most cases but for a really detailed manipulation with dates you should always look for some specialized third-party library.

Using Arrow:

>>> import arrow
>>> arrow.utcnow().format('dddd, D. M. YYYY')
'Friday, 6. 5. 2022'

Look at the full list of supported tokens.

橘和柠 2024-07-27 12:48:28

有点棘手,但对我

前任有用。 从 2021-02-01T00:00:00.000Z2021-02-1

from datetime import datetime

dateObj = datetime.strptime('2021-02-01T00:00:00.000Z','%Y-%m-%dT%H:%M:%S.%fZ')
dateObj.strftime('%Y-%m-{}').format(dateObj.day)

A little bit tricky but works for me

ex. from 2021-02-01T00:00:00.000Z to 2021-02-1

from datetime import datetime

dateObj = datetime.strptime('2021-02-01T00:00:00.000Z','%Y-%m-%dT%H:%M:%S.%fZ')
dateObj.strftime('%Y-%m-{}').format(dateObj.day)

回梦 2024-07-27 12:48:28

业余方法删除 Day & 的“0”前缀 月份,通过转换为“int”

dt = "08/01/2023"
dtArr = d.split("/")
print(str(int(x[0]))+'/'+str(int(x[1]))+'/'+str(int(x[2])))

An amateur approach to remove '0' prefix for Day & Month, by casting to 'int'

dt = "08/01/2023"
dtArr = d.split("/")
print(str(int(x[0]))+'/'+str(int(x[1]))+'/'+str(int(x[2])))
漆黑的白昼 2024-07-27 12:48:27

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

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

>>> import datetime
>>> datetime.datetime(2023, 1, 2).strftime("%Y/%-m/%-d")
'2023/1/2'

这只适用于 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:

>>> import datetime
>>> datetime.datetime(2023, 1, 2).strftime("%Y/%-m/%-d")
'2023/1/2'

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

╭ゆ眷念 2024-07-27 12:48:27

随着格式 自 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'
悲歌长辞 2024-07-27 12:48:27

根据 % 和字母之间的宽度和精度规范(例如表示月份中的“d”) /time.html" rel="noreferrer">http://docs.python.org/library/time.html ——但这绝对是一个不可移植的解决方案(例如,在我的 Mac 上不起作用; -)。 也许您可以在 strftime 之后使用字符串替换(或 RE,对于非常讨厌的格式)来解决这个问题? 例如:

>>> 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'
情徒 2024-07-27 12:48:27

这里是GNU C 库中 strftime() 支持的修饰符的文档。 (就像人们之前说的,它可能不可移植。)您可能感兴趣的是:

  • %e 而不是 %d 将用一个space

Python 文档 进行比较strftime() 格式代码%d 已记录:

%d:月份中的某天,以零填充的十进制数字形式。
示例:01、02、…、31

但是 %e 没有记录。 尽管没有记录它,但它似乎确实对我有用(运行 Linux):

>>> import datetime
>>> datetime.datetime(2023, 1, 1).strftime("%e")
' 1'

我不知道它是否适用于您的操作系统。

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

Compare with the Python documentation of strftime() Format Codes. %d is documented:

%d: Day of the month as a zero-padded decimal number.
Examples: 01, 02, …, 31

But %e is not documented. Even though it is not documented, it does seem to work for me regardless (running Linux):

>>> import datetime
>>> datetime.datetime(2023, 1, 1).strftime("%e")
' 1'

I don't know if it will work on your operating system.

安稳善良 2024-07-27 12:48:27
>>> 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'
℉服软 2024-07-27 12:48:27

聚会已经很晚了,但 %-d 对我来说很有效。

datetime.now().strftime('%B %-d, %Y') 产生类似于 "November 5, 2014"

欢呼 :)

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

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

cheers :)

遇到 2024-07-27 12:48:27

在 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

久随 2024-07-27 12:48:27

看看下面的-

>>> 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)
落墨 2024-07-27 12:48:27

我发现 Django 模板日期格式过滤器既快速又简单。 它去掉了前导零。 如果您不介意导入 Django 模块,请检查一下。

http://docs.djangoproject.com/en/dev/ref/模板/内置/#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')    
尝蛊 2024-07-27 12:48:27

只需使用 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'
无声无音无过去 2024-07-27 12:48:27

对于%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().

羅雙樹 2024-07-27 12:48:27

例如,即使在同一操作系统的不同版本之间,使用“%-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)
帅的被狗咬 2024-07-27 12:48:27

如果我们只想获取不带前导零的日期,我们可以

d = date.today()
day = int(d.strftime("%d"))

if we want to fetch only date without leading zero we can

d = date.today()
day = int(d.strftime("%d"))
水染的天色ゝ 2024-07-27 12:48:27

Python 3.6+:

from datetime import date
today = date.today()
text = "Today it is " + today.strftime(f"%A %B {today.day}, %Y")

Python 3.6+:

from datetime import date
today = date.today()
text = "Today it is " + today.strftime(f"%A %B {today.day}, %Y")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文