-2

New to Python, and have already spent 30 minutes reviewing old responses, but still can't figure this out.

'Year' variable is a string. Examples: 1990, 2010. I need to convert to date format, but just with the 4 year "digits". Tried the following, but none are working:

date1 = datetime.datetime.date('Year', "%Y")
datetime.datetime.strftime('Year', "%Y")
wcData.astype(str).apply(lambda x: pd.to_datetime('Year', format='%Y'))
df.astype(str).apply(lambda x: pd.to_datetime(x, format='%Y%m%d'))

Please help!

1 Answers1

0

You need datetime.datetime.strptime, not strftime:

import datetime

datetime.datetime.strptime("2010", "%Y")

Here's how to remember which one to use:

  • strPtime means "string -> parse -> time", that is, parse a string to create some kind of object that represents time;
  • strFtime means "string <- format <- time" (note the reversed arrows), that is, given an object that represents time, create a string representation of it using some format.
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • AttributeError: type object 'datetime.datetime' has no attribute 'datetime'. Received this error. – shanev13 Apr 29 '18 at 21:02
  • @shanev13, yeah, that the module has a class with the same name is pretty confusing. I've updated my answer. – ForceBru Apr 29 '18 at 21:06