I have tried searching other posts on here, but can't seem to solve this problem. I have a CSV file in which Year, Crash_Month, Crash_Day and Crash_Time are all seperate columns in the CSV 'data_dict'. I am trying to solve the below question. How would I go about this? I have tried to use a data frame, and pandas convert to datetime, but I'm not sure if this is the right approach. Many thanks
1 Answer
For the weekday part this should solve it: How do I get the day of week given a date? For the other parts, we can apply algebra operations on the datetime objects and define a range, see below:
if START_OF_SUMMER <= date <= END_OF_SUMMER:
season = SUMMER
Note: this question may be useful: https://stackoverflow.com/a/47545151/12684122 You can apply this same idea in time. For the invalid input check, you can use a simple type verify and see if the given date is a datetime object.
2 Comments
nickp
Thanks for that. I know how to do that usually, but can’t figure out how to combine all the coding to assign a datetime when the date and time is spread across multiple columns of the CSV, and then being able to assign another value (Eg season, time etc) to the datetime I need to create
olenscki
Hmm, I think that this can solve for you: [link] (journaldev.com/23365/python-string-to-datetime-strptime). The function
time.strptime(time_string, time_format) will convert a string to a datetime object. You just need to concatenate the strings of your df in one and then apply this function.