# Dates - Randomly generating DateTime values

**URL:** https://discourse.julialang.org/t/dates-randomly-generating-datetime-values/15156
**Category:** Data
**Created:** [September 19, 2018, 6:27am UTC](https://discourse.julialang.org/t/dates-randomly-generating-datetime-values/15156 "2018-09-19T06:27:29Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![mdsalerno](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mdsalerno/32/5539_2.png) [@mdsalerno](https://discourse.julialang.org/u/mdsalerno)
#### Post date: [September 19, 2018, 6:27am UTC](https://discourse.julialang.org/t/dates-randomly-generating-datetime-values/15156/1 "2018-09-19T06:27:29Z")

</div>

I have two DateTimes, dt1 \< dt2. What is a reasonable way to randomly generate a DateTime that is in between dt1 and dt2? I started off by trying

`dt3 = rand(dt1.instant.periods.value : dt2.instant.periods.value)`.

This gives me a randomly generated Int64 representation, but I do not know how to properly convert it back to a DateTime. Calling `DateTime(dt3)` doesn’t seem to parse correctly, presumably because it needs dt3 to be of type Millisecond as opposed to Int64, but I do not know how to convert from Int64 back to Millisecond.

---

<div class="post-metadata">

### Author: ![Simon\_Bolland](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/simon_bolland/32/8920_2.png) [@Simon\_Bolland](https://discourse.julialang.org/u/Simon_Bolland)
#### Post date: [September 19, 2018, 7:57am UTC](https://discourse.julialang.org/t/dates-randomly-generating-datetime-values/15156/2 "2018-09-19T07:57:33Z")

</div>

You could do

```julia
unix2datetime(rand(datetime2unix(dt1) : datetime2unix(dt2)))

```

but I suspect there’s a more efficient way

---

<div class="post-metadata">

### Author: ![Daneel](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/daneel/32/175_2.png) [@Daneel](https://discourse.julialang.org/u/Daneel)
#### Post date: [September 19, 2018, 8:16am UTC](https://discourse.julialang.org/t/dates-randomly-generating-datetime-values/15156/3 "2018-09-19T08:16:26Z")

</div>

It doesn’t feel very elegant and there is probably a better way but this is the way I came up with.

```julia
t0 = DateTime(2018,9,19)
t1 = DateTime(2018,9,19,10)
n = 5 # Number of values

t_random = t0 + Dates.Millisecond.(floor.(rand(n)*(t1-t0).value))

```
