Python 如何仅从日期时间对象中提取月份和日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40734440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract only the month and day from a datetime object?
提问by Candice Zhang
I was trying to do a scatterplot, and my x-axis needs to be each individual day in a year.
I first read in the datafile and get the date column, which are filled with integers like, 19800801. So I convert this integer
to datetime
by writing:
我试图做一个散点图,我的 x 轴需要是一年中的每一天。我首先读入数据文件并获取日期列,其中填充了整数,例如 19800801。所以我通过写入将其转换integer
为datetime
:
datetimes_0 = datetime.strptime(str(dates_pitts[0]), '%Y%m%d')
Then I want to extract only the month and day from the datetime object by writing:
然后我想通过编写只从 datetime 对象中提取月份和日期:
s = datetimes_0.strftime("%m%d")
I realized that they return value from strftime
is no longer a datetime object so I tried converting it back to datetime object by doing
我意识到他们的返回值strftime
不再是日期时间对象,所以我尝试通过执行将其转换回日期时间对象
s0= datetime.strptime(s, '%m%d')
But instead of giving me only the month and day, it gives me back the whole year, month and day. My question is how do I extract a datetime object of only the month and day(both) from a given integer like 19800801?
但它不是只给我月份和日期,而是给我整个年、月和日。我的问题是如何从给定的整数(如 19800801)中提取仅包含月份和日期(两者)的日期时间对象?
回答by Martin Evans
If you are trying to plot time based data in matplotlib, the usual approach is to first convert your dates into datatime
objects, and to then get matplotlib to convert these values into its own internal representation using the date2num()
function. Next, you can tell matplotlib how to format any ticks on the x-axis using a formatter, in this case a DateFormatter()
. So you could for example choose to display month and day for each tick.
如果您尝试在 matplotlib 中绘制基于时间的数据,通常的方法是首先将日期转换为datatime
对象,然后让 matplotlib 使用该date2num()
函数将这些值转换为它自己的内部表示。接下来,您可以告诉 matplotlib 如何使用格式化程序格式化 x 轴上的任何刻度,在本例中为DateFormatter()
. 例如,您可以选择为每个刻度显示月份和日期。
In this example, I display the month, with the day on the line below:
在这个例子中,我显示月份,下面一行显示日期:
from matplotlib import pyplot, dates
from datetime import datetime
data = [("19800801", 16), ("19800810", 10), ("19800901", 15), ("19800905", 14)]
xaxis = [datetime.strptime(d, '%Y%m%d') for d, v in data]
yaxis = [v for d, v in data]
ax = pyplot.gca()
xaxis = dates.date2num(xaxis) # Convert to maplotlib format
hfmt = dates.DateFormatter('%m\n%d')
ax.xaxis.set_major_formatter(hfmt)
pyplot.xlabel('Date')
pyplot.ylabel('Value')
pyplot.plot(xaxis, yaxis)
pyplot.tight_layout()
pyplot.show()
This would display as follows:
这将显示如下:
You could then extend this to use a DayLocator()
which tells matplotlib to place the xticks at exact day locations as follows:
然后,您可以扩展它以使用 a DayLocator()
,它告诉 matplotlib 将 xticks 放置在确切的日期位置,如下所示:
ax.xaxis.set_major_locator(dates.DayLocator())
Giving you:
给你:
回答by GracefulRestart
This will take an integer (supposing it is a valid epoch) and convert it into a python datetime object:
这将采用一个整数(假设它是一个有效的纪元)并将其转换为 python datetime 对象:
>>> import datetime
>>> date = datetime.datetime.fromtimestamp(19800801)
>>> print date.month
8
>>> print date.day
17
or using strftime (returns string and not a datetime object):
或使用 strftime (返回字符串而不是日期时间对象):
>>> datetime.datetime.fromtimestamp(19800801).strftime('%m%d')
'0817'
outputting the month and day as a single integer:
将月和日输出为单个整数:
>>> int(datetime.datetime.fromtimestamp(19800801).strftime('%m%d'))
817