Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract only the month and day from a datetime object?

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:

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:

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

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?

like image 849
Candice Zhang Avatar asked Nov 22 '16 05:11

Candice Zhang


1 Answers

This will take an integer (supposing it is a valid epoch) and convert it into a python datetime object:

>>> 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):

>>> 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
like image 152
GracefulRestart Avatar answered Nov 02 '22 05:11

GracefulRestart