Create DateTime from separate Date and Time fields

1847
3
Jump to solution
03-02-2021 03:18 AM
ToyotaT18
New Contributor III

I have a CSV dataset which has separate date and time fields. When imported to a feature class, the date field is of type 'date' and the time field is 'text'. I want to keep these separate, but add a new field to store a DateTime, ie a combination of the date and time. Can someone let me know how to enter this in the field calculator? I've tried using strptime() but it doesn't seem to let me cast the date as a string. Thanks.

0 Kudos
1 Solution

Accepted Solutions
DanPatterson
MVP Esteemed Contributor

datetime combine?

There are python examples

Easiest way to combine date and time strings to single datetime object using Python - Stack Overflow

Since you have already have the data in a field, it would be a matter of converting the time appropriately then combining.  The contents of your text time field would determine what the final formula would look like


... sort of retired...

View solution in original post

3 Replies
DanPatterson
MVP Esteemed Contributor

datetime combine?

There are python examples

Easiest way to combine date and time strings to single datetime object using Python - Stack Overflow

Since you have already have the data in a field, it would be a matter of converting the time appropriately then combining.  The contents of your text time field would determine what the final formula would look like


... sort of retired...
ToyotaT18
New Contributor III

Thanks Dan, I got it to work.

Expression: convertdatetime(!time_from!,!date_from!)

Code Block:

def convertdatetime(sTime, dDate):
    tTime = datetime.strptime(sTime, '%H:%M').time()
    dt = datetime.combine(dDate, tTime)
    return dt

 

I was hoping to wrap it up into a single statement but it doesn't work for some reason, something like:

datetime.combine(!date_from!, datetime.strptime(!time_from!, '%H:%M').time())

But that's ok, the solution works so I'm happy with that.

0 Kudos
MervynLotter
Occasional Contributor III

The easiest approach may be to first open up the CSV in Excel and then combine the two fields into one field using a formula such as "=TEXT(C2,"yyyy/m/dd ")&TEXT(D2,"hh:mm:ss")". But then once you add the CSV file to Pro, your new field will be recognised as a text field and not a date field, so then you need to run the Convert Time Field GP tool to convert it to a date field. 

0 Kudos