-2

I am parsing a .csv file which contains a column of dates in financial datetime format yyyymmdd, I need to remove weekends when writing some of the rows out to a different file.

I know to use datetime.weekdays() and then:

if some_datetime_object.datetime.weekday() != 6 or 1:
    f.write(some_row)

however, how would I convert a string parsed in from a csv to a datetime object to allow the weekday() function to be used.

Joe Smart
  • 751
  • 3
  • 10
  • 28

3 Answers3

1

You can use datetime.datetime.strptime:

import datetime
#example date strings
date1 = "20120423"
date2 = "2015-04-23"

datetime_object_1 = datetime.datetime.strptime(date1, '%Y%m%d')
datetime.datetime(2012, 4, 23, 0, 0)

datetime_object_2 = datetime.datetime.strptime(date1, '%Y-%m-%d')
datetime.datetime(2012, 4, 23, 0, 0)

Have a look at the bottom of this page to see all possible directives for the formatter of this function. You can parse almost any string with date/time data using the strptime method.

chris-sc
  • 1,698
  • 11
  • 21
0

You can convert to a datetime object using strptime. From here, you can use the weekdays method.

However, your conditions are inaccurate, if you only want to keep Monday through Friday. Note that weekday returns an integer from 0 to 6 with Monday being 0 and Sunday being 6.

Return the day of the week as an integer, where Monday is 0 and Sunday is 6.

This means you want to check if the returned value is 5 or 6.


The conditional you have will not work for another reason.

if some_datetime_object.datetime.weekday() != 6 or 1:

This is saying if the weekday is NOT Sunday OR True. You are short circuiting your conditional and forcing everything to be True. You need to make it something like this (with the appropriate values adjusted)

if some_datetime_object.datetime.weekday() != 6 and some_datetime_object.datetime.weekday() != 1:

I did this differently in the code below by using not in

if datetime.datetime.strptime(d, '%Y%m%d').weekday() not in (5,6):

import datetime

dates = [
    "20150801",
    "20150802",
    "20150803",
    "20150804",
    "20150805",
    "20150806",
    "20150807",
    "20150808",
    "20150809",
]

for d in dates:
    if datetime.datetime.strptime(d, '%Y%m%d').weekday() not in (5,6):
        print d

This outputs:

20150803
20150804
20150805
20150806
20150807
Andy
  • 49,085
  • 60
  • 166
  • 233
-1
from datetime import datetime
date_string = '20150501'
some_datetime_object = datetime(int(date_string[:4]), int(date_string[4:6]), int(date_string[6:]))

Your code however won't work, since that if statement is wrongly written. The correct way would be:

if some_datetime_object.datetime.weekday() not in (5,6)]:
francisco sollima
  • 7,952
  • 4
  • 22
  • 38