python_comm 0.4.2

to make writing python modules with rust easier.
Documentation
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
use {
    crate::use_m::*,
    chrono::{DateTime, Datelike, FixedOffset, NaiveDate, TimeZone, Utc},
    python_comm_macros::auto_func_name,
    std::time,
};

// https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat

// 格式代码
// b:YYYY-MM-DDTHH:MM:SS               文本, 假定为 +8 时区
// d-date                              零点, 假定为 +8 时区
// f-float                             浮点时间戳
// n:int                               整数时间戳
// s:YYYY-MM-DDTHH:MM:SS+08:00         文本, 含 +8 时区
// t-time                              标准格式, 含 +8 时区

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

/// 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 {
    bjtc_ds(&bj_date())
}

/// 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() -> DateTime<FixedOffset> {
    Utc::now().with_timezone(&FixedOffset::east_opt(8 * 3600).unwrap())
}

#[inline]
pub fn bj_time_init(year: i32, month: u32, day: u32, hour: u32, min: u32, sec: u32) -> DateTime<FixedOffset> {
    FixedOffset::east_opt(8 * 3600)
        .unwrap()
        .with_ymd_and_hms(year, month, day, hour, min, sec)
        .single()
        .unwrap()
}

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

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

/// 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 {
    bj_time().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 {
    bj_time().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]
#[auto_func_name]
pub fn bjtc_bd(text: &str) -> Result<NaiveDate, MoreError> {
    bjtc_sd(&bjtc_bs(text)).m(m!(fname))
}

/// See bjtc_bd
#[inline]
#[auto_func_name]
pub fn bjtc_bf(text: &str) -> Result<f64, MoreError> {
    bjtc_sf(&bjtc_bs(text)).m(m!(fname))
}

/// See bjtc_bd
#[inline]
#[auto_func_name]
pub fn bjtc_bn(text: &str) -> Result<i64, MoreError> {
    bjtc_sn(&bjtc_bs(text)).m(m!(fname))
}

/// See bjtc_bd
#[inline]
pub fn bjtc_bs(text: &str) -> String {
    format!("{}+08:00", text)
}

/// See bjtc_bd
#[inline]
#[auto_func_name]
pub fn bjtc_bt(text: &str) -> Result<DateTime<FixedOffset>, MoreError> {
    bjtc_st(&bjtc_bs(text)).m(m!(fname))
}

/// See bjtc_bd
#[inline]
pub fn bjtc_df(date: &NaiveDate) -> f64 {
    bjtc_dn(date) as f64
}

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

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

/// See bjtc_bd
#[inline]
pub fn bjtc_dt(date: &NaiveDate) -> DateTime<FixedOffset> {
    FixedOffset::east_opt(8 * 3600)
        .unwrap()
        .with_ymd_and_hms(date.year(), date.month(), date.day(), 0, 0, 0)
        .unwrap()
}

// fx

/// See bjtc_bd
#[inline]
#[auto_func_name]
pub fn bjtc_fb(timestamp: f64) -> Result<String, MoreError> {
    bjtc_ft(timestamp)
        .m(m!(fname, &format!("timestamp={}", timestamp)))
        .map(|time| bjtc_tb(&time))
}

/// See bjtc_bd
#[inline]
#[auto_func_name]
pub fn bjtc_fd(timestamp: f64) -> Result<NaiveDate, MoreError> {
    bjtc_ft(timestamp)
        .m(m!(fname, &format!("timestamp={}", timestamp)))
        .map(|time| bjtc_td(&time))
}

/// See bjtc_bd
#[inline]
#[auto_func_name]
pub fn bjtc_fs(timestamp: f64) -> Result<String, MoreError> {
    bjtc_ft(timestamp)
        .m(m!(fname, &format!("timestamp={}", timestamp)))
        .map(|time| bjtc_ts(&time))
}

/// See bjtc_bd
#[inline]
#[auto_func_name]
pub fn bjtc_ft(timestamp: f64) -> Result<DateTime<FixedOffset>, MoreError> {
    bjtc_nt(
        timestamp as i64,
        ((timestamp - (timestamp as i64 as f64)) * 1000.0) as u32,
    )
    .m(m!(fname, &format!("timestamp={}", timestamp)))
}

// nx

/// See bjtc_bd
#[inline]
#[auto_func_name]
pub fn bjtc_nb(timestamp: i64, millis: u32) -> Result<String, MoreError> {
    bjtc_nt(timestamp, millis)
        .m(m!(fname, &format!("timestamp={}, millis={}", timestamp, millis)))
        .map(|time| bjtc_tb(&time))
}

/// See bjtc_bd
#[inline]
#[auto_func_name]
pub fn bjtc_nd(timestamp: i64, millis: u32) -> Result<NaiveDate, MoreError> {
    bjtc_nt(timestamp, millis)
        .m(m!(fname, &format!("timestamp={}, millis={}", timestamp, millis)))
        .map(|time| bjtc_td(&time))
}

/// See bjtc_bd
#[inline]
#[auto_func_name]
pub fn bjtc_ns(timestamp: i64, millis: u32) -> Result<String, MoreError> {
    bjtc_nt(timestamp, millis)
        .m(m!(fname, &format!("timestamp={}, millis={}", timestamp, millis)))
        .map(|time| bjtc_ts(&time))
}

/// See bjtc_bd
#[inline]
#[auto_func_name]
pub fn bjtc_nt(timestamp: i64, millis: u32) -> Result<DateTime<FixedOffset>, MoreError> {
    DateTime::from_timestamp(timestamp, millis * 1000000)
        .map(|t| t.with_timezone(&FixedOffset::east_opt(8 * 3600).unwrap()))
        .ok_or(m!(fname, &format!("timestamp={}", timestamp), "more"))
}

// sx

/// See bjtc_bd
#[inline]
#[auto_func_name]
pub fn bjtc_sb(text: &str) -> String {
    text.replace("+08:00", "")
}

/// See bjtc_bd
#[inline]
#[auto_func_name]
pub fn bjtc_sd(text: &str) -> Result<NaiveDate, MoreError> {
    NaiveDate::parse_from_str(&text[..10], "%Y-%m-%d").m(m!(fname, text))
}

/// See bjtc_bd
#[inline]
#[auto_func_name]
pub fn bjtc_sf(text: &str) -> Result<f64, MoreError> {
    bjtc_st(text)
        .m(m!(fname, &format!("text={}", text)))
        .map(|time| bjtc_tf(&time))
}

/// See bjtc_dn
#[inline]
#[auto_func_name]
pub fn bjtc_sn(text: &str) -> Result<i64, MoreError> {
    bjtc_st(text)
        .m(m!(fname, &format!("text={}", text)))
        .map(|time| bjtc_tn(&time))
}

/// See bjtc_bd
#[inline]
#[auto_func_name]
pub fn bjtc_st(text: &str) -> Result<DateTime<FixedOffset>, MoreError> {
    DateTime::parse_from_str(text, "%Y-%m-%dT%H:%M:%S%:z").m(m!(fname, text))
}

// tx

/// See bjtc_bd
#[inline]
pub fn bjtc_tb(time: &DateTime<FixedOffset>) -> String {
    bjtc_sb(&bjtc_ts(time))
}

/// See bjtc_bd
#[inline]
pub fn bjtc_td(time: &DateTime<FixedOffset>) -> NaiveDate {
    time.date_naive()
}

/// See bjtc_bd
#[inline]
pub fn bjtc_tf(time: &DateTime<FixedOffset>) -> f64 {
    bjtc_tn(time) as f64
}

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

/// See bjtc_bd
#[inline]
pub fn bjtc_ts(time: &DateTime<FixedOffset>) -> String {
    bjtc_tt(time).format("%Y-%m-%dT%H:%M:%S%:z").to_string()
}

/// See bjtc_tt
#[inline]
pub fn bjtc_tt(time: &DateTime<FixedOffset>) -> DateTime<FixedOffset> {
    bjtc_nt(bjtc_tn(time), 0).unwrap()
}

//

/// 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 {
    match chrono::Duration::try_milliseconds(millis as i64) {
        Some(dur) => (*anchor + dur).timestamp_millis(),
        None => anchor.timestamp_micros(),
    }
}

/// 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, MoreError> {
    let elapsed = bjtc_nt(timestamp_millis / 1000, (timestamp_millis % 1000) as u32)
        .m(m!(fname, &format!("timestamp={}", timestamp_millis)))?
        - anchor.with_timezone(&FixedOffset::east_opt(8 * 3600).unwrap());

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

#[cfg(test)]
mod test {
    use chrono::Duration;

    use super::*;
    use std::thread;

    #[test]
    fn test_bjtc() {
        println!("date  {}", bj_date());
        println!("dates {}", bj_dates());
        println!("time  {}", bj_time());
        println!("times {}", bj_times());
        println!("timeb {}", bj_timeb());

        let b129 = "1970-01-02T09:00:00";
        let d129 = NaiveDate::from_ymd_opt(1970, 1, 2).unwrap();
        let e129 = FixedOffset::east_opt(7 * 3600)
            .unwrap()
            .with_ymd_and_hms(1970, 1, 2, 8, 0, 0)
            .single()
            .unwrap();
        let f129 = 86400.0 + 3600.0;
        let n129 = 86400 + 3600;
        let s129 = "1970-01-02T09:00:00+08:00";
        let t129 = bj_time_init(1970, 1, 2, 9, 0, 0);

        assert_eq!(bjtc_bd(b129).unwrap(), d129);
        assert_eq!(bjtc_bf(b129).unwrap(), f129);
        assert_eq!(bjtc_bn(b129).unwrap(), n129);
        assert_eq!(bjtc_bs(b129), s129);
        assert_eq!(bjtc_bt(b129).unwrap(), t129);

        assert_eq!(bjtc_df(&d129), f129 - 9.0 * 3600.0);
        assert_eq!(bjtc_dn(&d129), n129 - 9 * 3600);
        assert_eq!(bjtc_ds(&d129), "1970-01-02");
        assert_eq!(bjtc_dt(&d129), t129 - Duration::hours(9));

        assert_eq!(bjtc_fb(f129).unwrap(), b129);
        assert_eq!(bjtc_fd(f129).unwrap(), d129);
        assert_eq!(bjtc_fs(f129).unwrap(), s129);
        assert_eq!(bjtc_ft(f129).unwrap(), t129);

        assert_eq!(bjtc_nb(n129, 0).unwrap(), b129);
        assert_eq!(bjtc_nd(n129, 0).unwrap(), d129);
        assert_eq!(bjtc_ns(n129, 0).unwrap(), s129);
        assert_eq!(bjtc_nt(n129, 0).unwrap(), t129);

        assert_eq!(bjtc_sb(s129), b129);
        assert_eq!(bjtc_sd(s129).unwrap(), d129);
        assert_eq!(bjtc_sf(s129).unwrap(), f129);
        assert_eq!(bjtc_sn(s129).unwrap(), n129);
        assert_eq!(bjtc_st(s129).unwrap(), t129);

        assert_eq!(bjtc_tb(&e129), b129);
        assert_eq!(bjtc_td(&e129), d129);
        assert_eq!(bjtc_tf(&e129), f129);
        assert_eq!(bjtc_tn(&e129), n129);
        assert_eq!(bjtc_ts(&e129), s129);
        assert_eq!(bjtc_tt(&e129), t129);
    }

    #[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);
    }
}