Prajwal Mani Pradhan
Prajwal Mani Pradhan

Reputation: 397

Add days to datetime

I would like to add 24 hours or 1 day to my timedate variable in Stata.

read_date               Desired_date
2009-01-01 14:00:00     2009-01-02 14:00:00

I formatted my read_date with format read_date %tcCCYY-NN-DD_HH:MM:SS which worked without errors.

I have been trying to add days by adding 86400 seconds as: replace Desired_date = Desired_date+86400 It executes without errors but only time portion increases by an hour.

Upvotes: 0

Views: 716

Answers (1)

Nick Cox
Nick Cox

Reputation: 37208

The units of date-times in Stata are milliseconds as documented in help datetime. 86400 milliseconds is 86.4 seconds, not 1 hour.

You need to add the number of milliseconds in 1 day which is 24 * 60 * 60000, although it is neither necessary nor advisable to type that expression or its result. Adding cofd(1) adds the number of milliseconds in one day.

. di %tc  clock("4 May 2022 19:00:00", "DMY hms")
04may2022 19:00:00

. di %tc  clock("4 May 2022 19:00:00", "DMY hms") + cofd(1)
05may2022 19:00:00

I used display (di) for convenience with scalar constants. All you need to do is add cofd(1) in your replace statement.

.

Upvotes: 1

Related Questions