import arcpy, os
# Setup output location and overwrite status
arcpy.env.overwriteOutput = True
path = r"C:ProjectsTimeShips"
output_GDB = os.path.join(path, "Ships.gdb")
# Get time information from a layer in a layer file
lyrFile = arcpy.mp.LayerFile(os.path.join(path, "ShipPositions.lyrx"))
lyr = lyrFile.listLayers()[0]
lyrTime = lyr.time
# Set the time for which you want to select features in the time-enabled layer
fromTimeSelection = datetime.datetime(1776, 1, 1)
toTimeSelection = datetime.datetime(1777, 1, 1)
# Get the start and end time of the time enabled layer and its time field
startTime = lyrTime.startTime
endTime = lyrTime.endTime
timeField = lyrTime.startTimeField
# Check to see if the time for which you want to select features lies within the start and end time of the time enabled layer
if (fromTimeSelection < startTime or toTimeSelection > endTime):
print("The time specified for selecting features is not within the time extent of the layer")
else:
# Formulate the time query
timeQuery = f"{timeField} >= timestamp '{fromTimeSelection}' And
{timeField} < timestamp '{toTimeSelection}'"
# Process: Feature Class to Feature Class
arcpy.FeatureClassToFeatureClass_conversion(lyr, output_GDB, "Ships_1776", timeQuery, "", "")
# Add the new layer to a map and enable time
p = arcpy.mp.ArcGISProject(os.path.join(path, "ships.aprx"))
lyt = p.listLayouts('Ships')[0]
mf = lyt.listElements('MAPFRAME_ELEMENT', 'NoTimeMF')[0]
m = mf.map
m.addDataFromPath(os.path.join(output_GDB, "Ships_1776"))
l = m.listLayers("Ships_1776")[0]
l.enableTime()
mt = mf.time
mt.isTimeEnabled = True
# Save a copy of the project
p.saveACopy(os.path.join(path, "ships2.aprx"))