Vemund
Vemund

Reputation: 65

Update script with current date in python

I need some assistance updating a SQL script file with the current date. E.g. from python. In the SQL script I have a from->to date filter. To get this month's records. I will run this script from a CRON job on a Linux machine. And need to automatically update the from and to dates.

How?

;SQL script text to update. Before running sqlite3 shell command.
...
and date(tc1.time,'unixepoch')
   BETWEEN date('2012-03-01','start of month')
  and date('2012-04-01','start of month','+1 month','-1 day')
and date(tc2.time,'unixepoch')
 BETWEEN date('2012-03-01','start of month')
   and date('2012-04-01','start of month','+1 month','-1 day')

If date system date is 2012-03-30.

>date +"%Y-%m-%d"
2012-03-30

I wish to get from 2012-03-01 to 2012-04-01. If the date is 2012-04-20 or 2012-04-21.. I wish the output from 2012-04-01 to 2012-05-01.

Any suggestions?

Upvotes: 0

Views: 958

Answers (1)

kossmoboleat
kossmoboleat

Reputation: 1941

This should do the trick:

import datetime
d=datetime.date.today()
start_current_month=datetime.date(d.year,d.month,1)

if d.month==12:
    new_year=d.year+1
    new_month=1
else:
    new_year=d.year
    new_month=d.month+1

start_next_month=datetime.date(new_year,new_month,1)

str_start_current_month=start_current_month.isoformat()
str_start_next_month=start_next_month.isoformat()

str_start_current_month=start_current_month.isoformat()
str_start_next_month=start_next_month.isoformat()

Upvotes: 1

Related Questions