file creation and modification datetime in R

How to get when a file is created or modified in R

Here is how to get information when the file is created or modified in R. With help of R, you can extract this and other valuable information about files.

 

Get when a file is created or modified in R

It is simple to get the date and time of the file creation or modification in R by using the base function file.info.

The function file.info gives a bunch of information about the file, and it is easier for me to look at transposed results.

t(
  file.info("C:\\MyFolder\\test.csv")
  )

#      C:\\MyFolder\\test.csv
#size  "560444"                          
#isdir "FALSE"                           
#mode  "666"                             
#mtime "2020-12-23 10:08:21"             
#ctime "2020-12-08 11:16:16"             
#atime "2022-05-03 18:57:29"             
#exe   "no" 

As you can see in the results, there is a couple of timestamps that represent modification, creation, and last access.

Here is how to see the date-time when the file was created.

file.info("C:\\MyFolder\\test.csv")$ctime

#[1] "2020-12-08 11:16:16 EET"

Similarly, you can get the file modification date and time in R.

file.info("C:\\MyFolder\\test.csv")$mtime

#[1] "2020-12-23 10:08:21 EET"

If you need to extract only the creation date in R, here is how to do that.

as.Date(file.info("C:\\MyFolder\\test.csv")$ctime)

#[1] "2020-12-08"

 

Get creation or modification DateTime for each file in a folder in R

You can get information about multiple files in a directory. For example, you have a list of CSV files, and you want to know when each of them was created.

all_paths <-
  list.files(path = "C:\\MyFolder\\MyCSVFiles\\",
             pattern = "*.csv",
             full.names = TRUE)

Function file.info can easily get that by using a list of file paths.

file.info(all_paths)$ctime

#[1] "2020-11-10 16:11:02 EET" "2020-11-10 16:11:02 EET" "2020-11-13 12:19:49 EET"

You can combine that in a data frame.

data.frame("pahts" = all_paths, "ctime" = file.info(all_paths)$ctime)

#                                pahts               ctime
#1 C:\\MyFolder\\MyCSVFiles\\test1.csv 2020-11-10 16:11:02
#2 C:\\MyFolder\\MyCSVFiles\\test2.csv 2020-11-10 16:11:02
#3 C:\\MyFolder\\MyCSVFiles\\test3.csv 2020-11-13 12:19:49

Here is another example that is using the file paths to join them together.

 

Change file modification date and time in R

It is possible to change some of the file parameters. For example, if you want to change file modification date and time in R, then you can use the function Sys.setFileTime.

Sys.setFileTime("C:\\MyFolder\\test.csv", "2022-05-02")


file.info("C:\\MyFolder\\test.csv")$mtime

#[1] "2022-05-02 EEST"





Posted

in

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *