Adding Hours Minutes Seconds to a Date field

971
2
12-13-2018 02:51 PM
JoeBorgione
MVP Esteemed Contributor

Brain Teaser d'jour....

I have a data table that has a date field.  The values in the date field are only month/day/year (5/7/2018) and the client wants to keep the date portion and then get a Hours:Minutes:Seconds tacked on to it so the final value looks like:

5/7/2018 4:20:20 PM

The H:M:S are going to be 'phony'; that is I'll just generate them in a loop using a combination of time.now(), strftime and time.sleep(); that's not the problem. 

It's getting that new H:M:S together with the existing M/D/Year back into the datefield that is the teaser.  Been looking at strptime, and that gets pretty ugly pretty fast.  Just wondering if there might be an easier way?

Dan Patterson

Darren Wiens

Joshua Bixby

This generates H:M:S at one second interval:

>>> with arcpy.da.SearchCursor("AddTimeToSampleDate",'*') as cursor:
...     for row in cursor:
...         millerTime = datetime.now().strftime('%I:%M:%S %p')
...         print millerTime
...         time.sleep(1)
...         
03:47:08 PM
03:47:09 PM
03:47:10 PM
03:47:11 PM
03:47:12 PM
03:47:13 PM
03:47:14 PM
03:47:15 PM
03:47:16 PM
03:47:17 PM
03:47:18 PM
03:47:19 PM
03:47:20 PM
That should just about do it....
0 Kudos
2 Replies
RandyBurton
MVP Regular Contributor

Were you looking for something like this:

from datetime import timedelta
with arcpy.da.UpdateCursor("Point Test",['myDate']) as cursor:
    s = 1 # can be set to a time if needed:  ( hrs * 3600 ) + ( min * 60 ) + sec
    for row in cursor:
        row[0] += timedelta(seconds=s) # also minutes= hours= days=
        s += 1 # increment amount
        cursor.updateRow(row)
‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
JoeBorgione
MVP Esteemed Contributor

Thanks Randy- this worked for me:

from datetime import datetime
import time,arcpy
table = r'J:\WaterQuality\TestDictionary.gdb\AddTimeToSampleDate'
arcpy.MakeTableView_management("AddTimeToSampleDate",'TableView')

fields = ['OBJECTID', 'SAMPLEDATE']

with arcpy.da.UpdateCursor("AddTimeToSampleDate",fields) as cursor:
    for row in cursor:
        theDate = str(row[1]).split(' ')[0]
        year = theDate.split('-')[0]
        mnth = theDate.split('-')[1]
        day = theDate.split('-')[2]
        newDate = '{}/{}/{}'.format(mnth,day,year)
        theTime = datetime.now().strftime('%I:%M:%S %p')
        newDateTime = '{} {}'.format(newDate,theTime)
        finalDateTme = time.strptime(newDateTime,'%m/%d/%Y %I:%M:%S %p') 
        row[1] = newDateTime
        cursor.updateRow(row)
        print '{}'.format(newDateTime)
        time.sleep(1)

Yesterday I was watching the actual table attributes and not the table view I created, so I didn't notice the change.  Just ran it this morning....

That should just about do it....