0

I have a combination date/time string 20180104 06:09:36.234 from which I want to find the weekday in python, expecting to get the result for for the date (which is 04 January 2018) as "4" (ie Thursday) . Have searched far and wide to no avail.Can anyone help please? Thanks CJ

jpp
  • 159,742
  • 34
  • 281
  • 339
  • Possible duplicate of [How do I get the day of week given a date in Python?](https://stackoverflow.com/questions/9847213/how-do-i-get-the-day-of-week-given-a-date-in-python) – jpp Jan 31 '19 at 12:50

2 Answers2

3

See explanation of datetime.strptime

from datetime import datetime 

date_string = '20180104 06:09:36.234'
date = datetime.strptime(date_string, '%Y%m%d %H:%M:%S.%f')
print(date.isoweekday())  # 4
Tobey
  • 1,400
  • 1
  • 10
  • 25
  • 1
    doesn't that give 4 because it's the fourth day in January instead of the fourth day in the week? Better us [`date.isoweekday()`](https://docs.python.org/3/library/datetime.html#datetime.date.isoweekday) – Maarten Fabré Jan 31 '19 at 13:11
  • 1
    if he wants 4 for Thursday (and 7 for Sunday), you better use `isoweekday` instead of ´weekday´ – Maarten Fabré Jan 31 '19 at 14:48
0

Finally worked it out by various combinations of functions: Identify year, month, date, Convert to integer, Use datetime module.

import datetime
DateTime = '20180104 06:09:36.234'
Weekday =  datetime.date(int(DateTime[0:4]), int(DateTime[5:6]), 
int(DateTime[7:8])).weekday()
print("Weekday = " ,  Weekday)

Weekday = 3

Is there a better way??