Extract time from datetime, then evaluate

1520
4
07-10-2019 07:07 PM
MalcolmLittle
New Contributor III

Hello,

I have a full datetime field of type Date, e.g. 2018-11-28 05:05:44, that I have to evaluate values of only the time portion. Preferably I'd use the field calculator to add a value to a new field based on whether the time portion in the same record is greater than 05:00:00.

Looking for how to extract the time portion, then I can figure out the evaluation logic. The extraction part of getting the time out of datetime module is stymieing me.

Tags (2)
0 Kudos
4 Replies
DanPatterson_Retired
MVP Emeritus
# ---- playing with time

from datetime import datetime

n = datetime.now()

hms = (n.hour, n.minute, n.second)

"{} {} {}".format(*hms)
'22 45 13'

"{}h {}m {}s".format(*hms)
'22h 45m 13s'

# ---- just use 'dir' on the datetime object to get more options
JoeBorgione
MVP Emeritus

I used the same approach in a script recently. Using a search or update cursor, you can extract date elements in a similar fashion.  Here is the general idea:

import arcpy
table = r'X:\path\to\your\dataTable'

fields = ['SomeDateField']

with arcpy.da.SearchCursor(table, fields) as cursor:
    for row in cursor:
        print(row[0].year)
        print(row[0].month)
        print(row[0].day)
        print(row[0].hour)
        print(row[0].minute)
        print(row[0].second)

Instead of the print statement, you could set a variable to the value of a given element. In the case of an UpdateCursor, you would basically the same thing.  I used this snippet, to extract year and month elements from a date field, and then update two individual numeric fields accordingly:

fields =['Service_Date', 'Month', 'Year']
    
edit = arcpy.da.Editor(ws)
edit.startEditing(False,False)
edit.startOperation()

updateList = [1,2]
#update the new month and year fields
for i in updateList:
    with arcpy.da.UpdateCursor(table,fields) as cursor:
        for row in cursor:
            year = int(row[0].year)
            month = int(row[0].month)
            if i == 1:
                row[1] = month
                cursor.updateRow(row)
            elif i == 2:
                row[2] = year
                cursor.updateRow(row)
del cursor       
edit.stopOperation()
edit.stopEditing(True)
That should just about do it....
0 Kudos
LanceCole
MVP Regular Contributor

Malcolm, 

If you are working with a datetime parameter you can use the following to extract and evaluate the time portion.  The variable dt is a datetime and t is string representation of the time in the HH:MM, 24-hour format. Take a look at Python info on strftime for additional info output in different time formats

from datetime import datetime

dt = datetime.now()
t = dt.strftime("%H:%M")

if t == "08:00":
    print "Start Work"
elif t == "12:00":
    print "Lunch"
elif t == "17:00":
    print "Go Home"
elif t > "08:00" and t < "17:00":
    print "At Work"
else:
    print "No Match"‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

Please do keep in mind that strings are compared lexicographically so you may be better to use datetime objects depending upon your planed use, but this does work for most cases. 

MalcolmLittle
New Contributor III

Sorry guys, forgot to mention that I figured this out already. Used strftime() as Lance mentioned to extract time into a new variable, which got the time portion into a string with a 24 hour clock. With such a formatted string, I could easily do range evaluations.

0 Kudos