Skip to content

Period accepts datetime64 value #9869

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.16.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ Enhancements

- Allow conversion of values with dtype ``datetime64`` or ``timedelta64`` to strings using ``astype(str)`` (:issue:`9757`)
- ``get_dummies`` function now accepts ``sparse`` keyword. If set to ``True``, the return ``DataFrame`` is sparse, e.g. ``SparseDataFrame``. (:issue:`8823`)
- ``Period`` now accepts ``datetime64`` as value input. (:issue:`9054`)

.. _whatsnew_0161.api:

Expand Down
4 changes: 4 additions & 0 deletions pandas/src/period.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,10 @@ cdef class Period(object):
dt = value
if freq is None:
raise ValueError('Must supply freq for datetime value')
elif isinstance(value, np.datetime64):
dt = Timestamp(value)
if freq is None:
raise ValueError('Must supply freq for datetime value')
elif isinstance(value, date):
dt = datetime(year=value.year, month=value.month, day=value.day)
if freq is None:
Expand Down
6 changes: 6 additions & 0 deletions pandas/tseries/tests/test_period.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,13 @@ def test_period_constructor(self):

i1 = Period(date(2007, 1, 1), freq='M')
i2 = Period(datetime(2007, 1, 1), freq='M')
i3 = Period(np.datetime64('2007-01-01'), freq='M')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add a couple of more tests that have different numpy units,

e.g.

In [3]: np.datetime64('2007-01-01 00:00:00',dtype='M8[s]').dtype
Out[3]: dtype('<M8[s]')

i4 = Period(np.datetime64('2007-01-01 00:00:00Z'), freq='M')
i5 = Period(np.datetime64('2007-01-01 00:00:00.000Z'), freq='M')
self.assertEqual(i1, i2)
self.assertEqual(i1, i3)
self.assertEqual(i1, i4)
self.assertEqual(i1, i5)

i1 = Period('2007-01-01 09:00:00.001')
expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1000), freq='L')
Expand Down