Adjust date and time
Note
The Macro to Python converter is available from Metview version 5.22.0
Date/time literals and dates initialised from numbers in Macro are automatically converted to Python datetime objects:
Macro code |
Generated Python code |
---|---|
d = 2019-03-21
t = 03:11:32
d1 = 2021-03-21 05:11:32
d2 = date(20220321)
|
d = datetime.date(2019, 3, 21)
t = datetime.time(3, 11, 32)
d1 = datetime.datetime(2021, 3, 21, 5, 11, 32)
d2 = mv.date(20220321)
|
However, a problem arises when it comes down to date arithmetics. In Macro we can add floating point numbers to a date (1=1 day, 0.5=12 hours etc). However, in Python only a datetime.timedelta object can be added to a date. The converter is not able to resolve this, therefore every occurrence has to be checked and manually adjusted in the generated Python code. This is true for cases when:
we directly add a number to a date
we add the result of the
year()
,month()
,day()
,hour()
,minute()
orsecond()
Macro functions to a date (see function reference here)we add a number stored in a variable or generated by an expression to a date
The following examples demonstrate how the adjustment can be done in various use cases:
Macro |
Generated Python code |
Adjusted Python code |
---|---|---|
d = 2019-03-21
# add 1 day
d1 = d + 1
|
d = datetime.date(2019, 3, 21)
# not supported in datetime
d1 = d + 1
|
d = datetime.date(2019, 3, 21)
# correct
d1 = d + datetime.timedelta(days=1)
|
Macro |
Generated Python code |
Adjusted Python code |
---|---|---|
d = 2019-03-21
# add 1.5 day
d1 = d + 1.5
|
d = datetime.date(2019, 3, 21)
# error: not supported in datetime
d1 = d + 1.5
|
d = datetime.date(2019, 3, 21)
# correct
d1 = d + datetime.timedelta(days=1, hours=12)
|
Macro |
Generated Python code |
Adjusted Python code |
---|---|---|
d = 2019-03-21
# add 1 hours
d1 = d + hour(1)
|
d = datetime.date(2019, 3, 21)
# error: not supported in datetime
d1 = d + mv.hour(1)
|
d = datetime.date(2019, 3, 21)
# correct
d1 = d + datetime.timedelta(hours=1)
|