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
use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, Utc};
use python_comm_macros::auto_func_name;
use std::time;

/// Beijing time, date only
///
/// ## Usage
///
/// ```
/// use chrono::Datelike;
/// use python_comm::use_basic::*;
///
/// assert!(bj_date().year() >= 2021);
/// ```
///
#[inline]
pub fn bj_date() -> NaiveDate {
    bj_time().date()
}

/// Beijing time, date only, %Y-%m-%d format string
///
/// ## Usage
///
/// ```
/// use python_comm::use_basic::*;
///
/// assert!(bj_dates().starts_with("20"));
/// ````
///
#[inline]
pub fn bj_dates() -> String {
    bj_date().format("%Y-%m-%d").to_string()
}

/// Beijing time, date and time
///
/// ## Usage
///
/// ```
/// use chrono::Timelike;
/// use python_comm::use_basic::*;
///
/// assert!(bj_time().time().hour() >= 0);
/// ```
///
#[inline]
pub fn bj_time() -> NaiveDateTime {
    (Utc::now() + Duration::hours(8)).naive_utc()
}

/// Beijing time, date and time, %Y-%m-%d %H:%M:%S format string
///
/// ## Usage
///
/// ```
/// use python_comm::use_basic::*;
///
/// assert_eq!(bj_times().len(), 19);
/// ```
///
#[inline]
pub fn bj_times() -> String {
    bj_time().format("%Y-%m-%d %H:%M:%S").to_string()
}

/// Beijing time, timestamp
///
/// ## Usage
///
/// ```
/// use python_comm::use_basic::*;
///
/// let ts = bj_timestamp();
/// assert!(ts > 1623913021 && ts < 1623913021 + 86400 * 36500);
/// ```
///
#[inline]
pub fn bj_timestamp() -> i64 {
    Utc::now().timestamp()
}

/// Beijing time, timestamp, accurate to milliseconds
///
/// ## Usage
///
/// ```
/// use python_comm::use_basic::*;
///
/// let ts = bj_timestamp_millis();
/// assert!(ts > 1623913021000 && ts < 1623913021000 + 86400000 * 36500);
/// ```
///
#[inline]
pub fn bj_timestamp_millis() -> i64 {
    Utc::now().timestamp_millis()
}

/// bjtc_xy: Conversion between various expressions of Beijing time, x -> y
///
/// ## Conversion type
///
/// x,y is one of d,t,s,f,n
///
/// d: NaiveDate
///
/// t: NaiveDateTime
///
/// s: %Y-%m-%d or %Y-%m-%d %H:%M:%S
///
/// f: timestamp float
///
/// n: timestamp integer
///
/// ## Usage
///
/// ```
/// use python_comm::use_basic::*;
///
/// let ts = bj_timestamp();
/// let a = bjtc_nt(ts, 10).unwrap();
/// let b = bjtc_ts(&a);
/// let c = bjtc_st(&b).unwrap();
/// let d = bjtc_tf(&c);
/// assert_eq!(d as i64, ts);
/// ```
///
#[inline]
pub fn bjtc_df(date: &NaiveDate) -> f64 {
    bjtc_dn(date) as f64
}

/// See bjtc_df
#[inline]
pub fn bjtc_dn(date: &NaiveDate) -> i64 {
    bjtc_tn(&bjtc_dt(date))
}

/// See bjtc_df
#[inline]
pub fn bjtc_ds(date: &NaiveDate) -> String {
    date.format("%Y-%m-%d").to_string()
}

/// See bjtc_df
#[inline]
pub fn bjtc_dt(date: &NaiveDate) -> NaiveDateTime {
    date.and_hms(0, 0, 0)
}

// fx

/// See bjtc_df
#[inline]
#[auto_func_name]
pub fn bjtc_fd(timestamp: f64) -> Result<NaiveDate, anyhow::Error> {
    bjtc_nd(
        timestamp as i64,
        ((timestamp - (timestamp as i64 as f64)) * 1000.0) as u32,
    )
    .or_else(|err| raise_error!(__func__, timestamp, "\n", err))
}

/// See bjtc_df
#[inline]
#[auto_func_name]
pub fn bjtc_fs(timestamp: f64) -> Result<String, anyhow::Error> {
    Ok(bjtc_ts(&bjtc_ft(timestamp).or_else(|err| {
        raise_error!(__func__, timestamp, "\n", err)
    })?))
}

/// See bjtc_df
#[inline]
#[auto_func_name]
pub fn bjtc_ft(timestamp: f64) -> Result<NaiveDateTime, anyhow::Error> {
    bjtc_nt(
        timestamp as i64,
        ((timestamp - (timestamp as i64 as f64)) * 1000.0) as u32,
    )
    .or_else(|err| raise_error!(__func__, timestamp, "\n", err))
}

// nx

/// See bjtc_df
#[inline]
#[auto_func_name]
pub fn bjtc_nd(timestamp: i64, millis: u32) -> Result<NaiveDate, anyhow::Error> {
    Ok(bjtc_td(&bjtc_nt(timestamp, millis).or_else(|err| {
        raise_error!(__func__, timestamp, "\n", err)
    })?))
}

/// See bjtc_df
#[inline]
#[auto_func_name]
pub fn bjtc_ns(timestamp: i64, millis: u32) -> Result<String, anyhow::Error> {
    Ok(bjtc_ts(&bjtc_nt(timestamp, millis).or_else(|err| {
        raise_error!(__func__, timestamp, "\n", err)
    })?))
}

/// See bjtc_df
#[inline]
#[auto_func_name]
pub fn bjtc_nt(timestamp: i64, millis: u32) -> Result<NaiveDateTime, anyhow::Error> {
    NaiveDateTime::from_timestamp_opt(timestamp, millis * 1000000).ok_or(raise_error!(
        "raw",
        __func__,
        format!("无效时间戳 {}", timestamp)
    ))
}

// sx

/// See bjtc_df
#[inline]
#[auto_func_name]
pub fn bjtc_sd(text: &String) -> Result<NaiveDate, anyhow::Error> {
    NaiveDate::parse_from_str(text, "%Y-%m-%d")
        .or_else(|err| raise_error!(__func__, text, "\n", err))
}

/// See bjtc_df
#[inline]
#[auto_func_name]
pub fn bjtc_st(text: &String) -> Result<NaiveDateTime, anyhow::Error> {
    NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M:%S")
        .or_else(|err| raise_error!(__func__, text, "\n", err))
}

// tx

/// See bjtc_df
#[inline]
pub fn bjtc_td(time: &NaiveDateTime) -> NaiveDate {
    time.date()
}

/// See bjtc_df
#[inline]
pub fn bjtc_tf(time: &NaiveDateTime) -> f64 {
    bjtc_tn(time) as f64
}

/// See bjtc_dn
#[inline]
pub fn bjtc_tn(time: &NaiveDateTime) -> i64 {
    time.timestamp()
}

/// See bjtc_df
#[inline]
pub fn bjtc_ts(time: &NaiveDateTime) -> String {
    time.format("%Y-%m-%d %H:%M:%S").to_string()
}

//

/// Convert duration to timestamp, accurate to milliseconds
///
/// At the same time, record datetime as anchor, create time::instant as now,
/// then at any time after,
///
/// bjtc_from_duration convert now.duration() to timestamp,
///
/// bjtc_to_duration convert timestamp to now.duration()
///
/// ## Usage
///
/// ```
/// use chrono::Utc;
/// use python_comm::use_basic::*;
/// use std::{thread, time};
///
/// let anchor = Utc::now();
/// let now = time::Instant::now();
///
/// thread::sleep(time::Duration::from_millis(700));  // 0.7 seconds
/// let t1 = bjtc_from_duration(&anchor, now.elapsed().as_secs_f64() * 1000.0);
/// let t2 = bjtc_to_duration(&anchor, t1).unwrap();
/// let diff = t2.as_secs_f64() - 0.7;
/// assert!(diff > -0.5 && diff < 0.5);
///
/// let t1 = bjtc_from_duration(&anchor, 1000.0);
/// let t3 = bjtc_to_duration(&anchor, t1 - 1000);
/// assert_eq!(t3.is_err(), false);
/// assert_eq!(t3.unwrap().as_secs_f64(), 0.0);
/// let t4 = bjtc_to_duration(&anchor, t1 - 1001);
/// assert_eq!(t4.is_err(), true);
///
/// let diff = bjtc_to_duration(&anchor, bj_timestamp_millis())
///   .unwrap()
///   .as_secs_f64()
///   - 0.7;
/// assert!(diff > -0.5 && diff < 0.5);
/// ```
///
pub fn bjtc_from_duration(anchor: &DateTime<Utc>, millis: f64) -> i64 {
    (*anchor + chrono::Duration::milliseconds(millis as i64)).timestamp_millis()
}

/// Convert timestamp to duration, see bjtc_from_duration
#[auto_func_name]
pub fn bjtc_to_duration(
    anchor: &DateTime<Utc>,
    timestamp_millis: i64,
) -> Result<time::Duration, anyhow::Error> {
    let elapsed = bjtc_nt(timestamp_millis / 1000, (timestamp_millis % 1000) as u32)
        .or_else(|err| raise_error!(__func__, timestamp_millis, "\n", err))?
        - anchor.naive_utc();

    if elapsed.num_milliseconds() >= 0 {
        Ok(time::Duration::from_millis(
            elapsed.num_milliseconds() as u64
        ))
    } else {
        raise_error!(
            __func__,
            format!("{} 结果为负值 {}", timestamp_millis, elapsed.num_seconds())
        )
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::thread;

    #[test]
    fn test_bjtc_from_to_duration() {
        let anchor = Utc::now();
        let now = time::Instant::now();

        thread::sleep(time::Duration::from_millis(700)); // 0.7 秒
        let elapsed = now.elapsed().as_secs_f64();
        let t1 = bjtc_from_duration(&anchor, elapsed * 1000.0);
        let t2 = bjtc_to_duration(&anchor, t1).unwrap();
        let diff = t2.as_secs_f64() - elapsed;
        assert!(diff > -0.01 && diff < 0.01);

        let t1 = bjtc_from_duration(&anchor, 1000.0);
        let t3 = bjtc_to_duration(&anchor, t1 - 1000);
        assert_eq!(t3.is_err(), false);
        assert_eq!(t3.unwrap().as_secs_f64(), 0.0);
        let t4 = bjtc_to_duration(&anchor, t1 - 1001);
        assert_eq!(t4.is_err(), true);

        let diff = bjtc_to_duration(&anchor, bj_timestamp_millis())
            .unwrap()
            .as_secs_f64()
            - 0.7;
        assert!(diff > -0.1 && diff < 0.1);
    }
}