简体   繁体   English

如何随着日期的变化在python中格式化datetime?

[英]How to format datetime in python as date is doing?

In the shell: 在外壳中:

$ date
Do 27. Jun 15:13:13 CEST 2019

In python: 在python中:

>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2019, 6, 27, 15, 14, 51, 314560)
>>> a = datetime.now()
>>> a.strftime("%Y%m%d")
'20190627'

What is the format specifier needed to get the exactly same output as date , including evaluation of the locale settings? 要获得与date 完全相同的输出 (包括评估语言环境设置),需要使用哪种格式说明符?

you can use .strftime to get your own string format. 您可以使用.strftime获得自己的字符串格式。

in your case you want: 在您的情况下,您想要:

from datetime import datetime

now = datetime.now()

print(now.strftime("%a %d. %b %H:%M:%S %Z %Y"))

NOTE: how the day/month name are printed will be affected by your machine's current locale. 注意:日期/月份名称的打印方式将受到设备当前语言环境的影响。 you can set a custom datetime locale and timezone if you need specific ones. 您可以根据需要设置自定义的日期时间语言环境和时区。

Looks like you need to use the locale module 看起来您需要使用语言环境模块

Playing in the shell: 在外壳中玩:

$ date
Thu Jun 27 10:01:03 EDT 2019
$ LC_ALL=fr_FR.UTF-8 date
jeu. juin 27 10:01:12 EDT 2019

In python 在python中

$ LC_ALL=fr_FR.UTF-8 python
Python 2.7.5 (default, Jun 20 2019, 20:27:34) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> datetime.now().strftime("%c")
'Thu Jun 27 10:03:13 2019'

Hmm, I expected python to respect my environment. 嗯,我希望python能够尊重我的环境。 Let's force the issue: 让我们强制这个问题:

>>> import locale
>>> import os
>>> locale.setlocale(locale.LC_ALL, os.environ['LC_ALL'])
'fr_FR.UTF-8'
>>> datetime.now().strftime("%c")
'jeu. 27 juin 2019 10:04:48 '

Ah. 啊。


Reading a little further into the locale docs, I see 进一步阅读区域设置文档,我看到了

Initially, when a program is started, the locale is the C locale, no matter what the user's preferred locale is. 最初,启动程序时,无论用户首选的语言环境是什么,语言环境都是C语言环境。 The program must explicitly say that it wants the user's preferred locale settings by calling setlocale(LC_ALL, '') . 该程序必须通过调用setlocale(LC_ALL, '')明确表示要用户的首选语言环境设置。

from datetime import datetime
now=datetime.now()
year=now.strftime("%Y")
print("Year:",year)
month=now.strftime("%m")
print("Month:",month)
day=now.strftime("%d")
print("Day:",day)
time=now.strftime("%H:%M:%S")
print("Time:",time)
date_time=now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)

output: Year: 2019 Month: 06 Day: 27 Time: 21:19:33 date and time: 06/27/2019, 21:19:33 输出:年:2019月:06天:27时间:21:19:33日期和时间:06/27/2019,21:19:33

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

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