0

I have a text field featuring a 4 digit year. How would I assign a default month and day to the year in a new date field?

ex. 2010 needs to be converted to 1/1/2010

I attempted this in the field calculator:

def dt(year):
    dt_str = year
    dt_obj = datetime.datetime.strptime(dt_str, '%Y')
    return dt_obj

install date =

dt(!year!)
10
  • 1
    What was the result of this calculation? Any errors?
    – SMiller
    Commented Nov 16, 2018 at 21:21
  • Just kept running and never finished, so not sure.
    – Matt C
    Commented Nov 16, 2018 at 21:22
  • This might be due to overloading the method date in datetime with your new function date. Try changing the name of your function to be something else.
    – SMiller
    Commented Nov 16, 2018 at 21:23
  • Changed it to no avail. I did receive an error this time though. ERROR 000539: Traceback (most recent call last): File "<expression>", line 1, in <module> File "<string>", line 3, in dt TypeError: strptime() argument 1 must be str, not int
    – Matt C
    Commented Nov 16, 2018 at 21:32
  • That error means your year variable is an integer. Just add a line converting it -- dt_str = str(year)
    – SMiller
    Commented Nov 16, 2018 at 21:36

1 Answer 1

1

Change the function name to ensure it's not overloading date from datetime, or overloading a common short version of the datetime module (dt). Make sure you are importing datetime within the codeblock.

import datetime
def extractdate(year):
    #may need to change to str(year) if your input column is numeric
    #year = str(year)
    dt_obj = datetime.datetime.strptime(year, '%Y')
    return dt_obj

By default it will use January 1st, but if you want to control the month or date you can add more to the string and convert via strptime.

e.g. dt_obj = datetime.datetime.strptime(year+'03', '%Y%m') would give you all March 1st dates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.