Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove leading zeroes from timestamp %j%Y %H:%M

Tags:

date

regex

r

My timestamp is in the form

0992006 09:00

I need to remove the leading zeros to get this form:

992006 9:00

Here's the code I'm using now, which doesn't remove leading zeros:

prediction$TIMESTAMP <- as.character(format(prediction$TIMESTAMP, '%j%Y %H:%M'))
like image 574
kilojoules Avatar asked Sep 12 '14 06:09

kilojoules


1 Answers

Simplest way is to create your own boundary that asserts either the start of the string or a space precedes.

gsub('(^| )0+', '\\1', '0992006 09:00')
# [1] "992006 9:00"

You could do the same making the replacement exempt using a trick. \K resets the starting point of the reported match and any previously consumed characters are no longer included.

gsub('(^| )\\K0+', '', '0992006 09:00', perl=T)
# [1] "992006 9:00"

Or you could use sub and match until the second set of leading zeros.

sub('^0+([0-9]+ )0+', '\\1', '0992006 09:00')
# [1] "992006 9:00"

And to cover all possibilities, if you know that you will ever have a format like 0992006 00:00, simply remove the + quantifier from zero in the regular expression so it only removes the first leading zero.

like image 112
hwnd Avatar answered Sep 23 '22 00:09

hwnd