ChatGPT解决这个技术问题 Extra ChatGPT

如何以常规格式打印日期?

这是我的代码:

import datetime
today = datetime.date.today()
print(today)

这将打印: 2008-11-22 这正是我想要的。

但是,我有一个要附加的列表,然后突然间一切都变得“古怪”。这是代码:

import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print(mylist)

这将打印以下内容:

[datetime.date(2008, 11, 22)]

我怎样才能得到像 2008-11-22 这样的简单日期?

简短回答:通过应用 str()(对列表的每个元素),因为这正是 print 对您的单独 today 对象隐式执行的操作。

1
17 revs, 13 users 59%

为什么:日期是对象

在 Python 中,日期是对象。因此,当您操作它们时,您操作的是对象,而不是字符串或时间戳。

Python 中的任何对象都有两种字符串表示形式:

print 使用的正则表示可以使用 str() 函数获得。大多数情况下,它是最常见的人类可读格式,用于简化显示。所以 str(datetime.datetime(2008, 11, 22, 19, 53, 42)) 给你'2008-11-22 19:53:42'。

用于表示对象性质(作为数据)的替代表示。可以使用 repr() 函数获取它,并且可以方便地了解您在开发或调试时操作的数据类型。 repr(datetime.datetime(2008, 11, 22, 19, 53, 42)) 给你'datetime.datetime(2008, 11, 22, 19, 53, 42)'。

发生的情况是,当您使用 print 打印日期时,它使用了 str(),因此您可以看到一个不错的日期字符串。但是当您打印 mylist 时,您已经打印了一个对象列表,Python 尝试使用 repr() 来表示数据集。

The How:你想用它做什么?

好吧,当您操作日期时,请一直使用日期对象。他们获得了数千种有用的方法,并且大多数 Python API 都期望日期是对象。

当您想要显示它们时,只需使用 str()。在 Python 中,好的做法是显式转换所有内容。因此,当需要打印时,使用 str(date) 获取日期的字符串表示形式。

最后一件事。当您尝试打印日期时,您打印了 mylist。如果要打印日期,则必须打印日期对象,而不是它们的容器(列表)。

例如,您想打印列表中的所有日期:

for date in mylist :
    print str(date)

请注意,在特定情况下,您甚至可以省略 str(),因为 print 会为您使用它。但这不应该成为一种习惯:-)

实际案例,使用您的代码

import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0] # print the date object, not the container ;-)
2008-11-22

# It's better to always use str() because :

print "This is a new day : ", mylist[0] # will work
>>> This is a new day : 2008-11-22

print "This is a new day : " + mylist[0] # will crash
>>> cannot concatenate 'str' and 'datetime.date' objects

print "This is a new day : " + str(mylist[0]) 
>>> This is a new day : 2008-11-22

高级日期格式

日期具有默认表示,但您可能希望以特定格式打印它们。在这种情况下,您可以使用 strftime() 方法获取自定义字符串表示。

strftime() 需要一个字符串模式来解释您希望如何格式化您的日期。

例如:

print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'

"%" 之后的所有字母都代表某种格式:

%d 是天数(2 位数字,必要时以前导零为前缀)

%m 是月份编号(2 位数字,必要时以前导零为前缀)

%b 是月份的缩写(3 个字母)

%B 是完整的月份名称(字母)

%y 是年份数字的缩写(最后 2 位数字)

%Y 是完整的年份编号(4 位)

等等

Have a look at the official documentationMcCutchen's quick reference 你不可能全部都知道。

PEP3101 开始,每个对象都可以有自己的格式,任何字符串的方法格式都会自动使用它。对于日期时间,格式与 strftime 中使用的格式相同。所以你可以像上面一样做:

print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'

这种形式的好处是你还可以同时转换其他对象。
随着 Formatted string literals 的引入(自 Python 3.6,2016-12-23),这可以写成

import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'

本土化

如果您以正确的方式使用日期,日期可以自动适应当地的语言和文化,但这有点复杂。也许关于SO(堆栈溢出)的另一个问题;-)


顺便说一句,python 中几乎每种数据类型都是一个类(不可变对象除外,但它们可以被子类化)stackoverflow.com/questions/865911/…
“几乎”是什么意思? str 和 int 有一个类属性,其中包含“类型”,因此它们本身也有类,因为它们是元类类型的实例。
这正是术语的问题:type != class?,即具有类型属性(提供类型推断机制以限定对象)是否足够,或者实体应该表现为对象。我正在尝试在此处为自己解决此问题programmers.stackexchange.com/questions/164570/…
如果你是一个类的实例,你就是一个对象。为什么你需要它更复杂?
Python 中的每个值都是一个对象。每个对象都有一个类型。 "type" == "class" 正式(另请参阅 inspect.isclass 以确保)。人们倾向于对内置函数说“类型”,对其余的说“类”,但这并不重要
J
Josh Correia
import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

编辑:

Cees' suggestion 之后,我也开始使用时间:

import time
print time.strftime("%Y-%m-%d %H:%M")

您可以使用从 datetime import datetime,然后是 print datetime().now().strftime("%Y-%m-%d %H:%M")。只是语法不同。
from datetime import date; date.today().strftime("%Y-%m-%d") 对我来说仍然看起来很奇怪,但没有 import time 这是最好的。我认为 datetime 模块用于日期数学。
我最喜欢的是from datetime import datetime as dt,现在我们可以和dt.now()一起玩了
w
wjandrea

datedatetimetime 对象都支持 strftime(format) 方法,以在显式格式字符串的控制下创建表示时间的字符串。

这是格式代码及其指令和含义的列表。

%a  Locale’s abbreviated weekday name.
%A  Locale’s full weekday name.      
%b  Locale’s abbreviated month name.     
%B  Locale’s full month name.
%c  Locale’s appropriate date and time representation.   
%d  Day of the month as a decimal number [01,31].    
%f  Microsecond as a decimal number [0,999999], zero-padded on the left
%H  Hour (24-hour clock) as a decimal number [00,23].    
%I  Hour (12-hour clock) as a decimal number [01,12].    
%j  Day of the year as a decimal number [001,366].   
%m  Month as a decimal number [01,12].   
%M  Minute as a decimal number [00,59].      
%p  Locale’s equivalent of either AM or PM.
%S  Second as a decimal number [00,61].
%U  Week number of the year (Sunday as the first day of the week)
%w  Weekday as a decimal number [0(Sunday),6].   
%W  Week number of the year (Monday as the first day of the week)
%x  Locale’s appropriate date representation.    
%X  Locale’s appropriate time representation.    
%y  Year without century as a decimal number [00,99].    
%Y  Year with century as a decimal number.   
%z  UTC offset in the form +HHMM or -HHMM.
%Z  Time zone name (empty string if the object is naive).    
%%  A literal '%' character.

这就是我们可以用 Python 中的 datetime 和 time 模块做的事情

import time
import datetime

print "Time in seconds since the epoch: %s" %time.time()
print "Current date and time: ", datetime.datetime.now()
print "Or like this: ", datetime.datetime.now().strftime("%y-%m-%d-%H-%M")

print "Current year: ", datetime.date.today().strftime("%Y")
print "Month of year: ", datetime.date.today().strftime("%B")
print "Week number of the year: ", datetime.date.today().strftime("%W")
print "Weekday of the week: ", datetime.date.today().strftime("%w")
print "Day of year: ", datetime.date.today().strftime("%j")
print "Day of the month : ", datetime.date.today().strftime("%d")
print "Day of week: ", datetime.date.today().strftime("%A")

这将打印出如下内容:

Time in seconds since the epoch:    1349271346.46
Current date and time:              2012-10-03 15:35:46.461491
Or like this:                       12-10-03-15-35
Current year:                       2012
Month of year:                      October
Week number of the year:            40
Weekday of the week:                3
Day of year:                        277
Day of the month :                  03
Day of week:                        Wednesday

这解决了我的问题,而“更多投票的答案”没有。但我的问题与 OP 不同。我想将月份打印为文本(“二月”而不是“2”)
d
daviewales

使用 date.strftime。格式参数是 described in the documentation

这就是你想要的:

some_date.strftime('%Y-%m-%d')

这个考虑了语言环境。 (做这个)

some_date.strftime('%c')

C
Cees Timmerman

这更短:

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'

W
Waqas Ali
# convert date time to regular format.

d_date = datetime.datetime.now()
reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
print(reg_format_date)

# some other date formats.
reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p")
print(reg_format_date)
reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S")
print(reg_format_date)

输出

2016-10-06 01:21:34 PM
06 October 2016 01:21:34 PM
2016-10-06 13:21:34

b
b1_

甚至

from datetime import datetime, date

"{:%d.%m.%Y}".format(datetime.now())

出:'25.12.2013

或者

"{} - {:%d.%m.%Y}".format("Today", datetime.now())

出:“今天 - 2013 年 12 月 25 日”

"{:%A}".format(date.today())

出:“星期三”

'{}__{:%Y.%m.%d__%H-%M}.log'.format(__name__, datetime.now())

出:'__main____2014.06.09__16-56.log'


F
Flame of udun

简单的回答——

datetime.date.today().isoformat()

h
handle

Formatted string literal 中使用特定类型的 datetime 字符串格式(请参阅使用 str.format()nk9's answer。)(自 Python 3.6,2016-12-23 起):

>>> import datetime
>>> f"{datetime.datetime.now():%Y-%m-%d}"
'2017-06-15'

日期/时间格式指令未记录为 Format String Syntax 的一部分,而是记录在 datedatetimetimestrftime() 文档中。它们基于 1989 C 标准,但包括自 Python 3.6 以来的一些 ISO 8601 指令。


请注意,我还将此信息添加到接受的 answer 中。
strftime 并不真正包含“ISO 8601 输出”。有“指令”,但仅限于特定标记,如“星期几”,而不是整个 ISO 8601 时间戳,我一直觉得这很烦人。
f"{datetime.datetime.now().astimezone():%Y-%m-%dT%H:%M:%S.%f}"[:-3]+f"{datetime.datetime.now().astimezone():%z}" 也包括毫秒和时区
a
anon

我讨厌为了方便而导入太多模块的想法。我宁愿使用在这种情况下为 datetime 的可用模块,而不是调用新模块 time

>>> a = datetime.datetime(2015, 04, 01, 11, 23, 22)
>>> a.strftime('%Y-%m-%d %H:%M')
'2015-04-01 11:23'

我认为通过执行 a = datetime.datetime(2015, 04, 01, 23, 22).strftime('%Y-%m-%d %H:%M) 在一行代码中执行此操作会更有效
N
Nerveless_child

您需要将 datetime 对象转换为 str

以下代码对我有用:

import datetime

collection = []
dateTimeString = str(datetime.date.today())
collection.append(dateTimeString)
    
print(collection)

如果您需要更多帮助,请告诉我。


来吧 !不要鼓励新手存储字符串而不是日期对象。他将无法知道这是一个好主意还是一个坏主意......
e-satis:如果你只需要一个字符串,那有什么大不了的?我们一直将固件构建日期存储为字符串——当您只需要一个简单的时间戳(YAGNI 和所有)时,有时存储整个对象是多余的。
是的,在某些情况下确实如此。我的意思只是一个新手将无法识别这些案例。所以让我们从右脚开始:-)
I
Igal Serban

你可以做:

mylist.append(str(today))

W
Ward Taya

考虑到您要求做一些简单的事情来做您想做的事情,您可以:

import datetime
str(datetime.date.today())

L
Liran H

对于那些想要基于区域设置的日期而不包括时间的人,请使用:

>>> some_date.strftime('%x')
07/11/2019

i
izstas

由于 print today 返回您想要的,这意味着今天对象的 __str__ 函数返回您正在查找的字符串。

所以你也可以做mylist.append(today.__str__())


N
Nerveless_child
from datetime import date

def today_in_str_format():
    return str(date.today())

print (today_in_str_format())

如果这是您想要的,这将打印 2018-06-23 :)


N
Nerveless_child

您可能想将其附加为字符串?

import datetime

mylist = []
today = str(datetime.date.today())
mylist.append(today)

print(mylist)

D
Domenico Ruggiano

在 Python 中,您可以使用 datetime 模块中 datetimedatetime 类的 strftime() 方法格式化日期时间。

在您的具体情况下,您使用的是 datetime 中的 date 类。您可以使用以下代码段将 today 变量格式化为格式为 yyyy-MM-dd 的字符串:

import datetime

today = datetime.date.today()
print("formatted datetime: %s" % today.strftime("%Y-%m-%d"))

下面是一个更完整的例子:

import datetime
today = datetime.date.today()

# datetime in d/m/Y H:M:S format
date_time = today.strftime("%d/%m/%Y, %H:%M:%S")
print("datetime: %s" % date_time)

# datetime in Y-m-d H:M:S format
date_time = today.strftime("%Y-%m-%d, %H:%M:%S")
print("datetime: %s" % date_time)

# format date
date = today.strftime("%d/%m/%Y")
print("date: %s" % time)

# format time
time = today.strftime("%H:%M:%S")
print("time: %s" % time)

# day
day = today.strftime("%d")
print("day: %s" % day)

# month
month = today.strftime("%m")
print("month: %s" % month)

# year
year = today.strftime("%Y")
print("year: %s" % year)

更多指令:

https://i.stack.imgur.com/bOPCe.jpg

资料来源:

在 Python 中格式化日期时间

时间


R
Raphael Amoedo

您可以使用 easy_date 来简化:

import date_converter
my_date = date_converter.date_to_string(today, '%Y-%m-%d')

R
Remi Guan

我的答案的快速免责声明 - 我只学习 Python 大约 2 周,所以我绝不是专家;因此,我的解释可能不是最好的,我可能会使用不正确的术语。无论如何,它来了。

我在您的代码中注意到,当您声明变量 today = datetime.date.today() 时,您选择使用内置函数的名称来命名变量。

当您的下一行代码 mylist.append(today) 附加您的列表时,它附加了整个字符串 datetime.date.today(),您之前已将其设置为 today 变量的值,而不仅仅是附加 today()

一个简单的解决方案(尽管可能不是大多数编码人员在使用 datetime 模块时会使用的)是更改变量的名称。

这是我尝试过的:

import datetime
mylist = []
present = datetime.date.today()
mylist.append(present)
print present

并打印 yyyy-mm-dd


z
zondo

以下是将日期显示为(年/月/日)的方法:

from datetime import datetime
now = datetime.now()

print '%s/%s/%s' % (now.year, now.month, now.day)

t
tanmayee
import datetime
import time

months = ["Unknown","January","Febuary","Marchh","April","May","June","July","August","September","October","November","December"]
datetimeWrite = (time.strftime("%d-%m-%Y "))
date = time.strftime("%d")
month= time.strftime("%m")
choices = {'01': 'Jan', '02':'Feb','03':'Mar','04':'Apr','05':'May','06': 'Jun','07':'Jul','08':'Aug','09':'Sep','10':'Oct','11':'Nov','12':'Dec'}
result = choices.get(month, 'default')
year = time.strftime("%Y")
Date = date+"-"+result+"-"+year
print Date

通过这种方式,您可以获得像以下示例一样格式化的日期:22-Jun-2017


对于你可以在一行中得到的东西来说,代码太多了。使用 %b,您将获得前三个月的单词,而使用 %B,您将获得整个月。示例:datetime.datetime.now().strftime("%Y-%b-%d %H:%M:%S") 将返回 '2018-Oct-04 09:44:08'
U
U12-Forward

我不完全理解,但可以使用 pandas 以正确格式获取时间:

>>> import pandas as pd
>>> pd.to_datetime('now')
Timestamp('2018-10-07 06:03:30')
>>> print(pd.to_datetime('now'))
2018-10-07 06:03:47
>>> pd.to_datetime('now').date()
datetime.date(2018, 10, 7)
>>> print(pd.to_datetime('now').date())
2018-10-07
>>> 

和:

>>> l=[]
>>> l.append(pd.to_datetime('now').date())
>>> l
[datetime.date(2018, 10, 7)]
>>> map(str,l)
<map object at 0x0000005F67CCDF98>
>>> list(map(str,l))
['2018-10-07']

但它存储字符串但易于转换:

>>> l=list(map(str,l))
>>> list(map(pd.to_datetime,l))
[Timestamp('2018-10-07 00:00:00')]

做某事的整个依赖 python std 库有方法要做吗?
n
ntg

对于 pandas.Timestamp,可以使用 strftime(),例如:

utc_now = datetime.now()

对于等格式:

utc_now.isoformat()

For any format 例如:

utc_now.strftime("%m/%d/%Y, %H:%M:%S")