Last updated: 2023-08-15

Checks: 7 0

Knit directory: Pandas-30-R/

This reproducible R Markdown analysis was created with workflowr (version 1.7.0). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20221023) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 09ca4a2. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    dev/
    Ignored:    renv/

Unstaged changes:
    Modified:   renv.lock

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/bonus2-working-with-dates-in-Python.Rmd) and HTML (docs/bonus2-working-with-dates-in-Python.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
html be1850c Mena WANG 2023-08-15 Build site.
Rmd f6d01a1 Mena WANG 2023-08-15 more on datetime
html f5a895a Mena WANG 2023-08-13 Build site.
Rmd 7acb5aa Mena WANG 2023-08-13 working with dates

Introduction

It is many times tricky to work with dates. Here I will collect and share relevant functions that I found useful along the way.

Set up

# enable python in RMarkdown
library(reticulate)

datetime vs string

with the datetime package, we can easily transform between datetime/date object and its string representations.

import datetime

date_dt = datetime.datetime(2023, 8, 13, 0, 0, 0)
print(date_dt, type(date_dt))
2023-08-13 00:00:00 <class 'datetime.datetime'>
date = datetime.date(2023, 8, 13)
print(date, type(date))
2023-08-13 <class 'datetime.date'>
date_str = date.strftime('%Y-%m-%d')
print(date_str, type(date_str))
2023-08-13 <class 'str'>
date_dt_ = datetime.datetime.strptime(date_str, '%Y-%m-%d')
print(date_dt_, type(date_dt_))
2023-08-13 00:00:00 <class 'datetime.datetime'>
date_ = date_dt_.date()
print(date_, type(date_))
2023-08-13 <class 'datetime.date'>

Get a list of dates

Say the task here is to get all the first day of each month from 2023-01-01 to 2023-12-01.

method 1

dates = []

for month in range(1,13):
  date  = datetime.date(2023, month, 1)
  dates.append(date)
  
print(dates)
[datetime.date(2023, 1, 1), datetime.date(2023, 2, 1), datetime.date(2023, 3, 1), datetime.date(2023, 4, 1), datetime.date(2023, 5, 1), datetime.date(2023, 6, 1), datetime.date(2023, 7, 1), datetime.date(2023, 8, 1), datetime.date(2023, 9, 1), datetime.date(2023, 10, 1), datetime.date(2023, 11, 1), datetime.date(2023, 12, 1)]

method 2

Alternatively, we could just use monthly incremental offered by the relativedelta method in the dateutil package. Compare to method 1, there is no hard-coded year so it could expand across years seamlessly.

from dateutil.relativedelta import relativedelta

from_date = datetime.date(2022,1,1)
to_date = datetime.date(2023,12,1)
current_date = from_date
dates = []

while current_date <= to_date:
  dates.append(current_date)
  current_date += relativedelta(months = 1)

print(dates)
[datetime.date(2022, 1, 1), datetime.date(2022, 2, 1), datetime.date(2022, 3, 1), datetime.date(2022, 4, 1), datetime.date(2022, 5, 1), datetime.date(2022, 6, 1), datetime.date(2022, 7, 1), datetime.date(2022, 8, 1), datetime.date(2022, 9, 1), datetime.date(2022, 10, 1), datetime.date(2022, 11, 1), datetime.date(2022, 12, 1), datetime.date(2023, 1, 1), datetime.date(2023, 2, 1), datetime.date(2023, 3, 1), datetime.date(2023, 4, 1), datetime.date(2023, 5, 1), datetime.date(2023, 6, 1), datetime.date(2023, 7, 1), datetime.date(2023, 8, 1), datetime.date(2023, 9, 1), datetime.date(2023, 10, 1), datetime.date(2023, 11, 1), datetime.date(2023, 12, 1)]

Bonus

Say for whatever reason we want to pick 1 month from every 3 months, that is, we want the 1st, 4th, 7th, 10th etc months. This can be done very easily with enumerate.

selected_dates = []

for i, date in enumerate(dates):
  if i % 3 == 0:
    print(date)
    selected_dates.append(date)
2022-01-01
2022-04-01
2022-07-01
2022-10-01
2023-01-01
2023-04-01
2023-07-01
2023-10-01

sessionInfo()
R version 4.2.1 (2022-06-23 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19045)

Matrix products: default

locale:
[1] LC_COLLATE=English_Australia.utf8  LC_CTYPE=English_Australia.utf8   
[3] LC_MONETARY=English_Australia.utf8 LC_NUMERIC=C                      
[5] LC_TIME=English_Australia.utf8    

attached base packages:
[1] stats     graphics  grDevices datasets  utils     methods   base     

other attached packages:
[1] reticulate_1.30

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.11       pillar_1.9.0      compiler_4.2.1    bslib_0.5.0      
 [5] later_1.3.1       jquerylib_0.1.4   git2r_0.32.0      workflowr_1.7.0  
 [9] tools_4.2.1       digest_0.6.33     lattice_0.20-45   jsonlite_1.8.7   
[13] evaluate_0.21     lifecycle_1.0.3   tibble_3.2.1      png_0.1-8        
[17] pkgconfig_2.0.3   rlang_1.1.1       Matrix_1.4-1      cli_3.6.1        
[21] rstudioapi_0.15.0 yaml_2.3.7        xfun_0.39         fastmap_1.1.1    
[25] withr_2.5.0       stringr_1.5.0     knitr_1.43        fs_1.6.2         
[29] vctrs_0.6.3       sass_0.4.7        grid_4.2.1        rprojroot_2.0.3  
[33] glue_1.6.2        R6_2.5.1          fansi_1.0.4       rmarkdown_2.23   
[37] magrittr_2.0.3    whisker_0.4.1     promises_1.2.0.1  htmltools_0.5.5  
[41] renv_1.0.0        httpuv_1.6.11     utf8_1.2.3        stringi_1.7.12   
[45] cachem_1.0.8