0

I have a timestamp string column in my dataset.

from datetime import date
tmstmp = date('2018-05-01T23:20:07.317Z')

What I am trying to do id: write a function to extract the month, the day of the week and the hour of the day (0-24) from my timestamp string.

Thcodebove cod throws the error TypeError: an integer is required (got type str) when I try to cast the string as a date or a DateTime type.

How to cast the string into DateTime type and how to extract the days, month and hour data?

Also, it appears that the Z stands for zone, how to extract the zone name from the timestamp?

david nadal
  • 279
  • 4
  • 16
  • You have this tagged with Pandas, and with the SQL timestamp-with-timezone type, but you're just trying to use the `datetime` module. – abarnert Jun 21 '18 at 05:29
  • Use pandas `pd.to_datetime('2018-05-01T23:20:07.317Z')`, then the duplicate link will help you further – Bharath M Shetty Jun 21 '18 at 05:31
  • Anyway, you can't just call the constructor on a string, because Python has no idea which format your string is in. For example, if you give it `02-03-04`, would that mean 2 Mar 2004, 3 Feb 2004, or 4 Mar 2003? This is why the [`strptime`](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior) function exists. You have to read that, and figure out the format spec to match your string. Or you can use a library that _does_ try to guess, like `dateutil`, or Pandas. – abarnert Jun 21 '18 at 05:32
  • @Dark final_data['LogInTime'].to_datetime() gives me AttributeError: 'Series' object has no attribute 'to_datetime' – david nadal Jun 21 '18 at 05:33
  • 1
    Use it this way `pd.to_datetime(final_data['LoginTime'])` – Bharath M Shetty Jun 21 '18 at 05:34
  • @Dark thanks, I did final_data['LogInTime'] = pd.to_datetime(final_data['LogInTime']) and then I want to create another column which just has day of the week, another which has month.. but I cant do pd.to_day(final_data['LogInTime']) – david nadal Jun 21 '18 at 05:40
  • 1
    Once you have the datetime column use `.dt` accessor. The most voted answer in the linked question has it. For day use `final_data['LogInTime'].dt.day` – Bharath M Shetty Jun 21 '18 at 05:41

0 Answers0