[英]How to format datetime in python as date is doing?
在外壳中:
$ date
Do 27. Jun 15:13:13 CEST 2019
在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'
要获得与date
完全相同的输出 (包括评估语言环境设置),需要使用哪种格式说明符?
您可以使用.strftime
获得自己的字符串格式。
在您的情况下,您想要:
from datetime import datetime
now = datetime.now()
print(now.strftime("%a %d. %b %H:%M:%S %Z %Y"))
注意:日期/月份名称的打印方式将受到设备当前语言环境的影响。 您可以根据需要设置自定义的日期时间语言环境和时区。
看起来您需要使用语言环境模块
在外壳中玩:
$ date
Thu Jun 27 10:01:03 EDT 2019
$ LC_ALL=fr_FR.UTF-8 date
jeu. juin 27 10:01:12 EDT 2019
在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'
嗯,我希望python能够尊重我的环境。 让我们强制这个问题:
>>> 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 '
啊。
进一步阅读区域设置文档,我看到了
最初,启动程序时,无论用户首选的语言环境是什么,语言环境都是C语言环境。 该程序必须通过调用
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)
输出:年:2019月:06天:27时间:21:19:33日期和时间:06/27/2019,21:19:33
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.