Need help getting year from a date field (field calculator)

8985
12
06-03-2016 06:15 AM
RobBlash
Occasional Contributor III

I have dates (in a date field) of mixed formatting (1/21/2006 4:19:20 AM, 12/27/2007, etc.). I need to populate an integer field with just the year.

Based on this thread I'm trying to work my way through it but I can't get it figured out

d = datetime.datetime.strptime(!InstallDate!, "%d/%m/%Y")
justyr = datetime.datetime(d.year)

Any help would be appreciated!

12 Replies
JoshuaBixby
MVP Esteemed Contributor

Try this:

arcpy.time.FormatDate( !InstallDate!, 'yyyy')

RobBlash
Occasional Contributor III

Thanks, not sure why this was impossible to find (I searched and searched....).

0 Kudos
BlakeTerhune
MVP Regular Contributor

I didn't know arcpy had its own time. Put on your parachute pants and get ready for Esri Time! a parady of Hammer Time!

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

The ArcPy Time module is odd in that most of its functionality isn't documented at all, like the FormatDate method that has no references in the Desktop documentation except one to the old AML FORMATDATE function. 

0 Kudos
RobBlash
Occasional Contributor III

Thanks for mentioning this. I had found the documentation page you linked above, and I wondered why there wasn't a reference to .FormatDate()

How would you grade arcpy documentation overall? While I'm learning more and more about python I anticipate some head scratching along the way, which is of course minimized by good documentation. However, I didn't anticipate struggling so much to find this particular solution, after all finding DatePart('yyyy',[DateField]) is so much easier. I'm interested to hear the opinion of someone experienced.

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

I would rate the Python/ArcPy documentation as good, reaching towards very good.  The documentation is constantly improving, although different parts improve at different paces since different development teams work on their own Python documentation.

DanPatterson_Retired
MVP Emeritus

lurking behind the time stuff... is the fact that esri hasn't move from python 2 to python 3 completely... so little things like time zone had to be added to the arcpy stuff.  However, when one makes the move, all will be good because it has been there for a while

So if you aren't ready... python 2.7 countdown...

then you might want to look at this

8.1. datetime — Basic date and time types — Python 3.5.1 documentation

don't let time go by

0 Kudos
FernandoAlvarez1
New Contributor III

This was very helpful, the code allows you to replace 'yyyy' with "dddd" and "MMMM" to return days and months in string formats

0 Kudos
WesMiller
Regular Contributor III

0 Kudos