Acquire type of day from date field

617
5
Jump to solution
07-08-2019 07:36 AM
MalcolmLittle
New Contributor III

Hello,

I'm trying to fill a new string field with whether it is a "weekend" day or "weekday" day. I have an existing field that has full date-time values like this:

I'm not sure of the Python code needed in Calculate Field. This is what I have so far, but ArcPro rejects it, saying FullDateTime is not defined:

0 Kudos
1 Solution

Accepted Solutions
LanceCole
MVP Regular Contributor

Malcolm,

You are correct on the 0-6 for weekday(), I was thinking of isoweekday() which is 1-7 for Sunday through Saturday.  Sorry about that.

As you already are submitting a date type all you need is weekno = labelday.weekday() in your code to replace weekno = datetime.datetime(lableday).weekday() and you do not need the import statement. Something along the lines of the following using your naming:

def typodate(lableday):
  weekno = lableday.weekday()
  if weekno < 5:
    return "Weekday"
  else:
    return "Weekend"

View solution in original post

5 Replies
LanceCole
MVP Regular Contributor

You need to

1) pass (!FullDateTime!) to your function not (!DayType!)

2) move the "weekno = datetime.datetime(labelday).weekday()" line into your def statement rather than outside.  Another consideration, what type of data is FullDateTime: string, datetime, etc.

3) your first condition should be "weekno <= 5" as 1 through 5 are Monday through Friday.  6 and 7 are Saturday and Sunday for the weekday() function.

MalcolmLittle
New Contributor III

Thanks for the quick reply.

I ran it with your changes, yet I get an error "TypeError: an integer is required (got type datetime.datetime)". Perhaps this is because the FullDateTime field is a Date field. Is there a way to evaluate a Date field to acquire the type of day?

0 Kudos
LanceCole
MVP Regular Contributor

Malcolm,

Can you please 1) provide a copy of the revised code and 2) confirm the FullDateTime attribute is a type of datetime and not a string.  You can check this by right clicking on the attribute name in the table and selecting properties or just looking at the field information for the feature.

0 Kudos
MalcolmLittle
New Contributor III

This is my latest code with error:

This is the Field information regarding FullDateTime:

PS someone told me that datetime treats the days of the week as 0-6 values, starting with Monday at 0.

0 Kudos
LanceCole
MVP Regular Contributor

Malcolm,

You are correct on the 0-6 for weekday(), I was thinking of isoweekday() which is 1-7 for Sunday through Saturday.  Sorry about that.

As you already are submitting a date type all you need is weekno = labelday.weekday() in your code to replace weekno = datetime.datetime(lableday).weekday() and you do not need the import statement. Something along the lines of the following using your naming:

def typodate(lableday):
  weekno = lableday.weekday()
  if weekno < 5:
    return "Weekday"
  else:
    return "Weekend"