Select to view content in your preferred language

String to Datetime with Python in ArcGIS Pro

2687
3
Jump to solution
10-26-2023 08:08 AM
Thomas_Knaeuper
Esri Contributor

I want to create a datetime column in a feature class from a string field. The string field has this format: "%Y-%m-%dT%H:%M:%S" (for example: "2023-10-16T07:50:00"). When I use the gp tool "ConvertTimeField", some (about 10%) columns contain milliseconds, but the string does not contain milliseconds.

For example: string: 2023-10-16T07:50:25; output time: 10/16/2023 07:50:24; datetime object: datetime.datetime(2023, 10, 16, 7, 50, 24, 999000)

This also occurs when converting the time with "datetime.datetime.strptime()" when I run the script in the ArcGIS Pro Python window. If I use the same code from the script in ArcGIS Notebooks and Visual Studio Code, it works correctly.

Does anyone know this problem and can help me?
Thomas

0 Kudos
1 Solution

Accepted Solutions
Thomas_Knaeuper
Esri Contributor

Thank you very much for your help!
My ArcGIS Pro is running with version 3.1.3.

I have solved the problem myself. After changing the values in the attribute table, I used "arcpy.management.CopyFeatures" to copy the memory feature class to disk. If I don't run this tool or run it before, the datetime conversion works correctly.

View solution in original post

0 Kudos
3 Replies
DavidSolari
MVP Regular Contributor

I'm not sure where this ms level noise is coming from (especially with strptime) but this StackOverflow answer looks like a valid solution when combined with a good old Field Calculation run.

0 Kudos
VinceAngelo
Esri Esteemed Contributor

I've seen this behavior in Python often enough. I just assumed it was quirk of how Python operates -- if you don't fill all the values, it uses the value with which the object was initialized (the current time). So I usually combine strptime with a replace: to clear the microseconds property (and to either clear or force a UTC timezone)

 

import datetime

test_str = '2023-10-16T07:50:00'
new_dt = datetime.datetime.strptime(
                test_str,'%Y-%m-%dT%H:%M:%S').replace(
                microsecond=0,tzinfo=None)
print(new_dt.strftime('%Y-%m-%d %H:%M:%S.%f %Z'))

 

The funny thing is, I can't reproduce the problem in the Python in my Pro 3.1.1 or ArcMap 10.8.2 installs, so maybe that Python "feature" has been cleared.

What version of ArcGIS are you using for the ConvertTimeField utility?

- V

Thomas_Knaeuper
Esri Contributor

Thank you very much for your help!
My ArcGIS Pro is running with version 3.1.3.

I have solved the problem myself. After changing the values in the attribute table, I used "arcpy.management.CopyFeatures" to copy the memory feature class to disk. If I don't run this tool or run it before, the datetime conversion works correctly.

0 Kudos