1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
use super::*;
use crate::chunked_array::kernels::temporal::{
    date32_as_duration, date32_to_day, date32_to_month, date32_to_ordinal, date32_to_year,
    date64_as_duration, date64_to_day, date64_to_hour, date64_to_minute, date64_to_month,
    date64_to_nanosecond, date64_to_ordinal, date64_to_second,
};
use crate::prelude::*;
use chrono::{Datelike, NaiveDate, NaiveDateTime, NaiveTime};
use regex::Regex;

pub trait FromNaiveTime<T, N> {
    fn new_from_naive_time(name: &str, v: &[N]) -> Self;

    fn parse_from_str_slice(name: &str, v: &[&str], fmt: &str) -> Self;
}

fn parse_naive_time_from_str(s: &str, fmt: &str) -> Option<NaiveTime> {
    NaiveTime::parse_from_str(s, fmt).ok()
}

macro_rules! impl_from_naive_time {
    ($arrowtype:ident, $chunkedtype:ident, $func:ident) => {
        impl FromNaiveTime<$arrowtype, NaiveTime> for $chunkedtype {
            fn new_from_naive_time(name: &str, v: &[NaiveTime]) -> Self {
                let unit = v.iter().map($func).collect::<AlignedVec<_>>();
                ChunkedArray::new_from_aligned_vec(name, unit)
            }

            fn parse_from_str_slice(name: &str, v: &[&str], fmt: &str) -> Self {
                ChunkedArray::new_from_opt_iter(
                    name,
                    v.iter()
                        .map(|s| parse_naive_time_from_str(s, fmt).as_ref().map($func)),
                )
            }
        }
    };
}

impl_from_naive_time!(
    Time64NanosecondType,
    Time64NanosecondChunked,
    naive_time_to_time64_nanoseconds
);

pub trait AsNaiveTime {
    fn as_naive_time(&self) -> Vec<Option<NaiveTime>>;
}

pub fn parse_naive_datetime_from_str(s: &str, fmt: &str) -> Option<NaiveDateTime> {
    NaiveDateTime::parse_from_str(s, fmt).ok()
}

pub trait FromNaiveDateTime<T, N> {
    fn new_from_naive_datetime(name: &str, v: &[N]) -> Self;

    fn parse_from_str_slice(name: &str, v: &[&str], fmt: &str) -> Self;
}

macro_rules! impl_from_naive_datetime {
    ($arrowtype:ident, $chunkedtype:ident, $func:ident) => {
        impl FromNaiveDateTime<$arrowtype, NaiveDateTime> for $chunkedtype {
            fn new_from_naive_datetime(name: &str, v: &[NaiveDateTime]) -> Self {
                let unit = v.iter().map($func).collect::<AlignedVec<_>>();
                ChunkedArray::new_from_aligned_vec(name, unit)
            }

            fn parse_from_str_slice(name: &str, v: &[&str], fmt: &str) -> Self {
                ChunkedArray::new_from_opt_iter(
                    name,
                    v.iter()
                        .map(|s| parse_naive_datetime_from_str(s, fmt).as_ref().map($func)),
                )
            }
        }
    };
}

impl_from_naive_datetime!(Date64Type, Date64Chunked, naive_datetime_to_date64);

pub trait FromNaiveDate<T, N> {
    fn new_from_naive_date(name: &str, v: &[N]) -> Self;

    fn parse_from_str_slice(name: &str, v: &[&str], fmt: &str) -> Self;
}

pub fn naive_date_to_date32(nd: NaiveDate) -> i32 {
    let nt = NaiveTime::from_hms(0, 0, 0);
    let ndt = NaiveDateTime::new(nd, nt);
    naive_datetime_to_date32(&ndt)
}

pub fn parse_naive_date_from_str(s: &str, fmt: &str) -> Option<NaiveDate> {
    NaiveDate::parse_from_str(s, fmt).ok()
}

fn unix_time_naive_date() -> NaiveDate {
    NaiveDate::from_ymd(1970, 1, 1)
}

impl FromNaiveDate<Date32Type, NaiveDate> for Date32Chunked {
    fn new_from_naive_date(name: &str, v: &[NaiveDate]) -> Self {
        let unit = v
            .iter()
            .map(|v| naive_date_to_date32(*v))
            .collect::<AlignedVec<_>>();
        ChunkedArray::new_from_aligned_vec(name, unit)
    }

    fn parse_from_str_slice(name: &str, v: &[&str], fmt: &str) -> Self {
        ChunkedArray::new_from_opt_iter(
            name,
            v.iter().map(|s| {
                parse_naive_date_from_str(s, fmt)
                    .as_ref()
                    .map(|v| naive_date_to_date32(*v))
            }),
        )
    }
}

pub trait AsNaiveDateTime {
    fn as_naive_datetime(&self) -> Vec<Option<NaiveDateTime>>;
}

macro_rules! impl_as_naive_datetime {
    ($ca:ty, $fun:ident) => {
        impl AsNaiveDateTime for $ca {
            fn as_naive_datetime(&self) -> Vec<Option<NaiveDateTime>> {
                self.into_iter().map(|opt_t| opt_t.map($fun)).collect()
            }
        }
    };
}

impl_as_naive_datetime!(Date32Chunked, date32_as_datetime);
impl_as_naive_datetime!(Date64Chunked, date64_as_datetime);

pub trait AsNaiveDate {
    fn as_naive_date(&self) -> Vec<Option<NaiveDate>>;
}

impl AsNaiveDate for Date32Chunked {
    fn as_naive_date(&self) -> Vec<Option<NaiveDate>> {
        self.into_iter()
            .map(|opt_t| {
                opt_t.map(|v| {
                    let dt = date32_as_datetime(v);
                    NaiveDate::from_ymd(dt.year(), dt.month(), dt.day())
                })
            })
            .collect()
    }
}

pub trait AsDuration<T> {
    fn as_duration(&self) -> ChunkedArray<T>;
}

impl AsNaiveTime for Time64NanosecondChunked {
    fn as_naive_time(&self) -> Vec<Option<NaiveTime>> {
        self.into_iter()
            .map(|opt_t| opt_t.map(time64_nanosecond_as_time))
            .collect()
    }
}

impl AsDuration<DurationMillisecondType> for Date32Chunked {
    fn as_duration(&self) -> DurationMillisecondChunked {
        self.apply_kernel_cast(date32_as_duration)
    }
}

impl AsDuration<DurationMillisecondType> for Date64Chunked {
    fn as_duration(&self) -> DurationMillisecondChunked {
        self.apply_kernel_cast(date64_as_duration)
    }
}

impl Utf8Chunked {
    fn get_first_val(&self) -> Result<&str> {
        let idx = match self.first_non_null() {
            Some(idx) => idx,
            None => {
                return Err(PolarsError::HasNullValues(
                    "Cannot determine date parsing format, all values are null".into(),
                ))
            }
        };
        let val = self.get(idx).expect("should not be null");
        Ok(val)
    }

    fn sniff_fmt_date64(&self) -> Result<&'static str> {
        let val = self.get_first_val()?;
        let pat = r"^\d{4}-\d{1,2}-\d{1,2} \d{2}:\d{2}:\d{2}\s*$";
        let reg = Regex::new(pat).expect("wrong regex");
        if reg.is_match(val) {
            return Ok("%Y-%m-%d %H:%M:%S");
        }
        let pat = r"^\d{4}/\d{1,2}/\d{1,2} \d{2}:\d{2}:\d{2}\s*$";
        let reg = Regex::new(pat).expect("wrong regex");
        if reg.is_match(val) {
            return Ok("%Y/%m/%d %H:%M:%S");
        }
        Err(PolarsError::Other(
            "Could not find an appropriate format to parse dates, please define a fmt".into(),
        ))
    }

    fn sniff_fmt_date32(&self) -> Result<&'static str> {
        let val = self.get_first_val()?;
        let pat = r"^\d{4}-\d{1,2}-\d{1,2}\s*$";
        let reg = Regex::new(pat).expect("wrong regex");
        if reg.is_match(val) {
            return Ok("%Y-%m-%d");
        }

        let pat = r"^\d{1,2}-\d{1,2}-\d{4}\s*$";
        let reg = Regex::new(pat).expect("wrong regex");
        if reg.is_match(val) {
            return Ok("%d-%m-%Y");
        }

        let pat = r"^\d{4}/\d{1,2}/\d{1,2}\s*$";
        let reg = Regex::new(pat).expect("wrong regex");
        if reg.is_match(val) {
            return Ok("%Y/%m/%d %H:%M:%S");
        }
        Err(PolarsError::Other(
            "Could not find an appropriate format to parse dates, please define a fmt".into(),
        ))
    }

    pub fn as_date32(&self, fmt: Option<&str>) -> Result<Date32Chunked> {
        let fmt = match fmt {
            Some(fmt) => fmt,
            None => self.sniff_fmt_date32()?,
        };

        let mut ca: Date32Chunked = match self.null_count() {
            0 => self
                .into_no_null_iter()
                .map(|s| parse_naive_date_from_str(s, fmt).map(naive_date_to_date32))
                .collect(),
            _ => self
                .into_iter()
                .map(|opt_s| {
                    let opt_nd =
                        opt_s.map(|s| parse_naive_date_from_str(s, fmt).map(naive_date_to_date32));
                    match opt_nd {
                        None => None,
                        Some(None) => None,
                        Some(Some(nd)) => Some(nd),
                    }
                })
                .collect(),
        };
        ca.rename(self.name());
        Ok(ca)
    }

    pub fn as_date64(&self, fmt: Option<&str>) -> Result<Date64Chunked> {
        let fmt = match fmt {
            Some(fmt) => fmt,
            None => self.sniff_fmt_date64()?,
        };

        let mut ca: Date64Chunked = match self.null_count() {
            0 => self
                .into_no_null_iter()
                .map(|s| {
                    parse_naive_datetime_from_str(s, fmt).map(|dt| naive_datetime_to_date64(&dt))
                })
                .collect(),
            _ => self
                .into_iter()
                .map(|opt_s| {
                    let opt_nd = opt_s.map(|s| {
                        parse_naive_datetime_from_str(s, fmt)
                            .map(|dt| naive_datetime_to_date64(&dt))
                    });
                    match opt_nd {
                        None => None,
                        Some(None) => None,
                        Some(Some(nd)) => Some(nd),
                    }
                })
                .collect(),
        };
        ca.rename(self.name());
        Ok(ca)
    }
}

impl Date64Chunked {
    /// Extract month from underlying NaiveDateTime representation.
    /// Returns the year number in the calendar date.
    pub fn year(&self) -> Int32Chunked {
        self.apply_kernel_cast::<_, Int32Type>(date64_to_month)
    }

    /// Extract month from underlying NaiveDateTime representation.
    /// Returns the month number starting from 1.
    ///
    /// The return value ranges from 1 to 12.
    pub fn month(&self) -> UInt32Chunked {
        self.apply_kernel_cast::<_, UInt32Type>(date64_to_month)
    }

    /// Extract day from underlying NaiveDateTime representation.
    /// Returns the day of month starting from 1.
    ///
    /// The return value ranges from 1 to 31. (The last day of month differs by months.)
    pub fn day(&self) -> UInt32Chunked {
        self.apply_kernel_cast::<_, UInt32Type>(date64_to_day)
    }
    /// Extract hour from underlying NaiveDateTime representation.
    /// Returns the hour number from 0 to 23.
    pub fn hour(&self) -> UInt32Chunked {
        self.apply_kernel_cast::<_, UInt32Type>(date64_to_hour)
    }

    /// Extract minute from underlying NaiveDateTime representation.
    /// Returns the minute number from 0 to 59.
    pub fn minute(&self) -> UInt32Chunked {
        self.apply_kernel_cast::<_, UInt32Type>(date64_to_minute)
    }

    /// Extract second from underlying NaiveDateTime representation.
    /// Returns the second number from 0 to 59.
    pub fn second(&self) -> UInt32Chunked {
        self.apply_kernel_cast::<_, UInt32Type>(date64_to_second)
    }

    /// Extract second from underlying NaiveDateTime representation.
    /// Returns the number of nanoseconds since the whole non-leap second.
    /// The range from 1,000,000,000 to 1,999,999,999 represents the leap second.
    pub fn nanosecond(&self) -> UInt32Chunked {
        self.apply_kernel_cast::<_, UInt32Type>(date64_to_nanosecond)
    }

    /// Returns the day of year starting from 1.
    ///
    /// The return value ranges from 1 to 366. (The last day of year differs by years.)
    pub fn ordinal(&self) -> UInt32Chunked {
        self.apply_kernel_cast::<_, UInt32Type>(date64_to_ordinal)
    }
}

impl Date32Chunked {
    /// Extract month from underlying NaiveDateTime representation.
    /// Returns the year number in the calendar date.
    pub fn year(&self) -> Int32Chunked {
        self.apply_kernel_cast::<_, Int32Type>(date32_to_year)
    }

    /// Extract month from underlying NaiveDateTime representation.
    /// Returns the month number starting from 1.
    ///
    /// The return value ranges from 1 to 12.
    pub fn month(&self) -> UInt32Chunked {
        self.apply_kernel_cast::<_, UInt32Type>(date32_to_month)
    }

    /// Extract day from underlying NaiveDateTime representation.
    /// Returns the day of month starting from 1.
    ///
    /// The return value ranges from 1 to 31. (The last day of month differs by months.)
    pub fn day(&self) -> UInt32Chunked {
        self.apply_kernel_cast::<_, UInt32Type>(date32_to_day)
    }

    /// Returns the day of year starting from 1.
    ///
    /// The return value ranges from 1 to 366. (The last day of year differs by years.)
    pub fn ordinal(&self) -> UInt32Chunked {
        self.apply_kernel_cast::<_, UInt32Type>(date32_to_ordinal)
    }
}