I thought it would be necessary when manipulating the date of csv output by scraping in the future.
-You can specify the date in the csv name to be created by using the current time in the application. -Operation of csv written in the csv file -Date type to string type and vice versa
test.py
from datetime import datetime
now = datetime.now()
print(now)
-----result-----
2020-10-26 20:39:01.825495
test.py
from datetime import datetime
# 2018/11/11 can be done in the same way
str_date = 'November 11, 2018'
#strptime turns a string into a date
#strftime turns the date into a string
one_date = datetime.strptime(str_date, '%Y year%m month%d day')
print(one_date)
-----result-----
2018-11-11 00:00:00
from datetime import datetime
from datetime import timedelta
str_date = '2018/11/11'
base_date = datetime.strptime(str_date, '%Y/%m/%d')
print(base_date)
-----result-----
2018-11-11 00:00:00
----------------
#10 days ago
before_10days = base_date - timedelta(days=10)
#10 days later
before_10days = base_date - timedelta(days=10)
print(before_10days)
-----result-----
2018-11-01 00:00:00
day.csv
2016-10-01
2016-10-02
2016-10-03
2016-10-04
2016-10-05
2016-10-06
2016-10-07
2016-10-08
2016-10-09
2016-10-10
2016-10-11
2016-10-12
2016-10-13
2016-10-14
day.py
from datetime import datetime
#read csv
with open('day.csv', encoding='utf-8') as f:
for row in f:
day = datetime.strptime(row.rstrip(), '%Y-%m-%d')
print(f'{day:%Y/%m/%d}')
-----result-----
2016/10/02
2016/10/03
2016/10/04
2016/10/05
2016/10/06
2016/10/07
2016/10/08
2016/10/09
2016/10/10
2016/10/11
2016/10/12
2016/10/13
2016/10/14
What's new in Python 3.8 f'{Expression =}' The expression itself can now be output. When outputting the format f'{expression =: format}'
test.py
from datetime import datetime
from datetime import timedelta
main_date ='2016-10-12'
#String → date
base_day = datetime.strptime(main_date,'%Y-%m-%d')
#Date one week ago
before_7days = base_day - timedelta(days=7)
#Select csv file
with open('day.csv', encoding='utf-8') as f:
for row in f:
#Character string → date Delete line break at the end of line
day = datetime.strptime(row.rstrip(), '%Y-%m-%d')
#print(day)
#2016-10-02 00:00:00
#2016-10-03 00:00:00
#~
#2016-10-14 00:00:00
#2016-10-Show applicable items for 12 to 7 days
if before_7days <= day < base_day:
#Y/m/In d format
print(f'{day:%Y/%m/%d}')
-----reult-----
2016/10/05
2016/10/06
2016/10/07
2016/10/08
2016/10/09
2016/10/10
2016/10/11
Recommended Posts