Home > Enterprise >  Modifying the timezone of a timestamp in a filename using R
Modifying the timezone of a timestamp in a filename using R

Time:11-10

I'm currently working with a large dataset of acoustic recordings (.wav) that were recorded to the SD card with the default filename in UTC in the format YYYYMMDD_HHMMSS:

20220606_152100.wav 20220606_152200.wav 20220606_152300.wav

For the analysis, I am including temporal factors and need the local datetime for every recording, which is 5 hours behind UTC. I can easily get the UTC datetime from the file name and convert it to UTC in R:

wav <- list.files(datadir, pattern="*.WAV$",full.names=FALSE, recursive=TRUE)
filename <- tools::file_path_sans_ext(basename(FI))
recordedtime <- strptime(filename,"%Y%m%d_%H%M%S",tz="UTC")
datetime <- (recordedtime-hours(5))

...which works well for analysis in R, but as I'm working with subsets in other programs I'd like to be able to rename all of the files to reduce the risk that I forget to convert (or do it more than once) when I'm going between analyses. I have been able to change individual file names in the working directory manually:

file.rename("20220606_152100.wav","20220606_102100.wav")

But obviously with thousands of files, I can't justify doing this individually.

Thank you in advance for any help or suggestions :-)

CodePudding user response:

If we have a set of file names, we can use

library(lubridate)
format(ymd_hms(str1) %m-% hours(5), "%Y%m%d_%H%M%S.wav")
[1] "20220606_102100.wav"

data

str1 <- "20220606_152100.wav"

CodePudding user response:

The following extends your workflow to create new filepaths based on the adjusted times, which you can then pass to file.rename() along with the vector of original paths.

library(tools)
library(lubridate)

wavpaths <- list.files(datadir, pattern="*.wav$", full.names=TRUE, recursive=TRUE)

utctime <- wavpaths |>
  file_path_sans_ext() |>
  basename() |>
  strptime("%Y%m%d_%H%M%S", tz="UTC")

localtime <- strftime(utctime - hours(5), "%Y%m%d_%H%M%S")

renpaths <- file.path(dirname(wavpaths), paste0(localtime, ".wav"))

file.rename(wavpaths, renpaths)

Result:

# original paths
wavpaths
#> [1] "wavs/20220606_152100.wav"         "wavs/subdir1/20220606_021000.wav"
#> [3] "wavs/subdir1/20220606_230000.wav"

# new paths
list.files(datadir, pattern="*.wav$", full.names=TRUE, recursive=TRUE)
#> [1] "wavs/20220606_102100.wav"         "wavs/subdir1/20220605_211000.wav"
#> [3] "wavs/subdir1/20220606_180000.wav"

Example file structure setup:

datadir <- "wavs"
dir.create(datadir)
dir.create(file.path(datadir, "subdir1"))
file.create(file.path(datadir, "20220606_152100.wav"))
file.create(file.path(datadir, "subdir1", c("20220606_021000.wav", "20220606_230000.wav")))

Created on 2022-11-09 with reprex v2.0.2

  • Related