-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
data.py
2511 lines (1893 loc) · 68.2 KB
/
data.py
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import base64
import datetime
import hashlib
import json
import math
import operator
import re
import time
import typing
from code import compile_command
from enum import Enum
from typing import Any, Literal, Optional, TypeVar
from urllib.parse import parse_qsl, quote, urlencode, urljoin, urlparse, urlunparse
import pytz
from click import secho
from dateutil import parser
from dateutil.parser import ParserError
from dateutil.relativedelta import relativedelta
import frappe
from frappe.desk.utils import slug
DateTimeLikeObject = str | datetime.date | datetime.datetime
NumericType = int | float
TimespanOptions = Literal[
"last week",
"last month",
"last quarter",
"last 6 months",
"last year",
"yesterday",
"today",
"tomorrow",
"this week",
"this month",
"this quarter",
"this year",
"next week",
"next month",
"next quarter",
"next 6 months",
"next year",
]
if typing.TYPE_CHECKING:
from PIL.ImageFile import ImageFile as PILImageFile
T = TypeVar("T")
DATE_FORMAT = "%Y-%m-%d"
TIME_FORMAT = "%H:%M:%S.%f"
DATETIME_FORMAT = f"{DATE_FORMAT} {TIME_FORMAT}"
TIMEDELTA_DAY_PATTERN = re.compile(
r"(?P<days>[-\d]+) day[s]*, (?P<hours>\d+):(?P<minutes>\d+):(?P<seconds>\d[\.\d+]*)"
)
TIMEDELTA_BASE_PATTERN = re.compile(r"(?P<hours>\d+):(?P<minutes>\d+):(?P<seconds>\d[\.\d+]*)")
URLS_HTTP_TAG_PATTERN = re.compile(
r'(href|src){1}([\s]*=[\s]*[\'"]?)((?:http)[^\'">]+)([\'"]?)'
) # href='https://...
URLS_NOT_HTTP_TAG_PATTERN = re.compile(
r'(href|src){1}([\s]*=[\s]*[\'"]?)((?!http)[^\'" >]+)([\'"]?)'
) # href=/assets/...
URL_NOTATION_PATTERN = re.compile(
r'(:[\s]?url)(\([\'"]?)((?!http)[^\'" >]+)([\'"]?\))'
) # background-image: url('/assets/...')
DURATION_PATTERN = re.compile(r"^(?:(\d+d)?((^|\s)\d+h)?((^|\s)\d+m)?((^|\s)\d+s)?)$")
HTML_TAG_PATTERN = re.compile("<[^>]+>")
MARIADB_SPECIFIC_COMMENT = re.compile(r"#.*")
class Weekday(Enum):
Sunday = 0
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6
def get_first_day_of_the_week() -> str:
return frappe.get_system_settings("first_day_of_the_week") or "Sunday"
def get_start_of_week_index() -> int:
return Weekday[get_first_day_of_the_week()].value
def is_invalid_date_string(date_string: str) -> bool:
"""Return True if the date string is invalid or None or empty."""
# dateutil parser does not agree with dates like "0001-01-01" or "0000-00-00"
return not isinstance(date_string, str) or (
(not date_string) or (date_string or "").startswith(("0001-01-01", "0000-00-00"))
)
def getdate(
string_date: Optional["DateTimeLikeObject"] = None, parse_day_first: bool = False
) -> datetime.date | None:
"""
Convert string date (yyyy-mm-dd) to datetime.date object.
If no input is provided, current date is returned.
"""
if not string_date:
return get_datetime().date()
if isinstance(string_date, datetime.datetime):
return string_date.date()
elif isinstance(string_date, datetime.date):
return string_date
if is_invalid_date_string(string_date):
return None
try:
return parser.parse(string_date, dayfirst=parse_day_first).date()
except ParserError:
frappe.throw(
frappe._("{} is not a valid date string.").format(frappe.bold(string_date)),
title=frappe._("Invalid Date"),
)
def get_datetime(
datetime_str: Optional["DateTimeLikeObject"] | tuple | list = None,
) -> datetime.datetime | None:
"""Return the below mentioned values based on the given `datetime_str`:
* If `datetime_str` is None, returns datetime object of current datetime
* If `datetime_str` is already a datetime object, returns the same
* If `datetime_str` is a timedelta object, returns the same
* If `datetime_str` is a list or tuple, returns a datetime object
* If `datetime_str` is a date object, returns a datetime object
* If `datetime_str` is a valid date string, returns a datetime object for the same
* If `datetime_str` is an invalid date string, returns None
"""
if datetime_str is None:
return now_datetime()
if isinstance(datetime_str, datetime.datetime | datetime.timedelta):
return datetime_str
elif isinstance(datetime_str, list | tuple):
return datetime.datetime(datetime_str)
elif isinstance(datetime_str, datetime.date):
return datetime.datetime.combine(datetime_str, datetime.time())
if is_invalid_date_string(datetime_str):
return None
try:
return datetime.datetime.strptime(datetime_str, DATETIME_FORMAT)
except ValueError:
return parser.parse(datetime_str)
def get_timedelta(time: str | datetime.timedelta | None = None) -> datetime.timedelta | None:
"""Return `datetime.timedelta` object from string value of a valid time format.
Return None if `time` is not a valid format.
Args:
time (str | datetime.timedelta): A valid time representation. This string is parsed
using `dateutil.parser.parse`. Examples of valid inputs are:
'0:0:0', '17:21:00', '2012-01-19 17:21:00'. Checkout
https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parse
Return:
datetime.timedelta: Timedelta object equivalent of the passed `time` string
"""
if isinstance(time, datetime.timedelta):
return time
time = time or "0:0:0"
try:
try:
t = parser.parse(time)
except ParserError as e:
if "day" in e.args[1] or "hour must be in" in e.args[0]:
return parse_timedelta(time)
raise e
return datetime.timedelta(
hours=t.hour, minutes=t.minute, seconds=t.second, microseconds=t.microsecond
)
except Exception:
return None
def to_timedelta(time_str: str | datetime.time) -> datetime.timedelta:
"""Return a `datetime.timedelta` object from the given string or `datetime.time` object.
If the given argument is not a string or a `datetime.time` object, it is returned as is.
"""
if isinstance(time_str, datetime.time):
time_str = str(time_str)
if isinstance(time_str, str):
t = parser.parse(time_str)
return datetime.timedelta(
hours=t.hour, minutes=t.minute, seconds=t.second, microseconds=t.microsecond
)
else:
return time_str
@typing.overload
def add_to_date(
date,
years=0,
months=0,
weeks=0,
days=0,
hours=0,
minutes=0,
seconds=0,
as_string: Literal[False] = False,
as_datetime: Literal[False] = False,
) -> datetime.date:
...
@typing.overload
def add_to_date(
date,
years=0,
months=0,
weeks=0,
days=0,
hours=0,
minutes=0,
seconds=0,
as_string: Literal[False] = False,
as_datetime: Literal[True] = True,
) -> datetime.datetime:
...
@typing.overload
def add_to_date(
date,
years=0,
months=0,
weeks=0,
days=0,
hours=0,
minutes=0,
seconds=0,
as_string: Literal[True] = True,
as_datetime: bool = False,
) -> str:
...
def add_to_date(
date: DateTimeLikeObject,
years=0,
months=0,
weeks=0,
days=0,
hours=0,
minutes=0,
seconds=0,
as_string=False,
as_datetime=False,
) -> DateTimeLikeObject:
"""Adds `days` to the given date"""
if date is None:
date = now_datetime()
if hours:
as_datetime = True
if isinstance(date, str):
as_string = True
if " " in date:
as_datetime = True
try:
date = parser.parse(date)
except ParserError:
frappe.throw(frappe._("Please select a valid date filter"), title=frappe._("Invalid Date"))
date = date + relativedelta(
years=years, months=months, weeks=weeks, days=days, hours=hours, minutes=minutes, seconds=seconds
)
if as_string:
if as_datetime:
return date.strftime(DATETIME_FORMAT)
else:
return date.strftime(DATE_FORMAT)
else:
return date
def add_days(date: DateTimeLikeObject, days: NumericType) -> DateTimeLikeObject:
"""Return a new date after adding the given number of `days` to the given `date`."""
return add_to_date(date, days=days)
def add_months(date: DateTimeLikeObject, months: NumericType) -> DateTimeLikeObject:
"""Return a new date after adding the given number of `months` to the given `date`."""
return add_to_date(date, months=months)
def add_years(date: DateTimeLikeObject, years: NumericType) -> DateTimeLikeObject:
"""Return a new date after adding the given number of `years` to the given `date`."""
return add_to_date(date, years=years)
def date_diff(string_ed_date: DateTimeLikeObject, string_st_date: DateTimeLikeObject) -> int:
"""Return the difference between given two dates in days."""
return days_diff(string_ed_date, string_st_date)
def days_diff(string_ed_date: DateTimeLikeObject, string_st_date: DateTimeLikeObject) -> int:
"""Return the difference between given two dates in days."""
return (getdate(string_ed_date) - getdate(string_st_date)).days
def month_diff(string_ed_date: DateTimeLikeObject, string_st_date: DateTimeLikeObject) -> int:
"""Return the difference between given two dates in months."""
ed_date = getdate(string_ed_date)
st_date = getdate(string_st_date)
return (ed_date.year - st_date.year) * 12 + ed_date.month - st_date.month + 1
def time_diff(string_ed_date: DateTimeLikeObject, string_st_date: DateTimeLikeObject) -> datetime.timedelta:
"""Return the difference between given two dates as `datetime.timedelta` object."""
return get_datetime(string_ed_date) - get_datetime(string_st_date)
def time_diff_in_seconds(string_ed_date: DateTimeLikeObject, string_st_date: DateTimeLikeObject) -> float:
"""Return the difference between given two dates in seconds."""
return time_diff(string_ed_date, string_st_date).total_seconds()
def time_diff_in_hours(string_ed_date: DateTimeLikeObject, string_st_date: DateTimeLikeObject) -> float:
"""Return the difference between given two dates in hours."""
return round(float(time_diff(string_ed_date, string_st_date).total_seconds()) / 3600, 6)
def now_datetime() -> datetime.datetime:
"""Return the current datetime in system timezone."""
dt = convert_utc_to_system_timezone(datetime.datetime.now(pytz.UTC))
return dt.replace(tzinfo=None)
def get_timestamp(date: Optional["DateTimeLikeObject"] = None) -> float:
"""Return the Unix timestamp (seconds since Epoch) for the given `date`.
If `date` is None, the current timestamp is returned.
"""
return time.mktime(getdate(date).timetuple())
def get_eta(from_time: DateTimeLikeObject, percent_complete) -> str:
diff = time_diff(now_datetime(), from_time).total_seconds()
return str(datetime.timedelta(seconds=(100 - percent_complete) / percent_complete * diff))
def _get_system_timezone():
return frappe.get_system_settings("time_zone") or "Asia/Kolkata" # Default to India ?!
def get_system_timezone() -> str:
"""Return the system timezone."""
if frappe.local.flags.in_test:
return _get_system_timezone()
return frappe.cache.get_value("time_zone", _get_system_timezone)
def convert_utc_to_timezone(utc_timestamp: datetime.datetime, time_zone: str) -> datetime.datetime:
from pytz import UnknownTimeZoneError, timezone
if utc_timestamp.tzinfo is None:
utc_timestamp = timezone("UTC").localize(utc_timestamp)
try:
return utc_timestamp.astimezone(timezone(time_zone))
except UnknownTimeZoneError:
return utc_timestamp
def get_datetime_in_timezone(time_zone: str) -> datetime.datetime:
"""Return the current datetime in the given timezone (e.g. 'Asia/Kolkata')."""
utc_timestamp = datetime.datetime.now(pytz.UTC)
return convert_utc_to_timezone(utc_timestamp, time_zone)
def convert_utc_to_system_timezone(utc_timestamp: datetime.datetime) -> datetime.datetime:
"""Return the given UTC `datetime` timestamp in system timezone."""
time_zone = get_system_timezone()
return convert_utc_to_timezone(utc_timestamp, time_zone)
def now() -> str:
"""Return current datetime as `yyyy-mm-dd hh:mm:ss`."""
if frappe.flags.current_date:
return (
getdate(frappe.flags.current_date).strftime(DATE_FORMAT)
+ " "
+ now_datetime().strftime(TIME_FORMAT)
)
else:
return now_datetime().strftime(DATETIME_FORMAT)
def nowdate() -> str:
"""Return current date as `yyyy-mm-dd`."""
return now_datetime().strftime(DATE_FORMAT)
def today() -> str:
"""Return today's date in `yyyy-mm-dd` format."""
return nowdate()
def get_abbr(string: str, max_len: int = 2) -> str:
"""Return the abbreviation of the given string.
Examples:
* "John Doe" => "JD"
* "Jenny Jane Doe" => "JJ" (default, `max_len` = 2)
* "Jenny Jane Doe" => "JJD" (`max_len` = 3)
Return "?" if the given string is empty.
"""
abbr = ""
for part in string.split(" "):
if len(abbr) < max_len and part:
abbr += part[0]
return abbr or "?"
def nowtime() -> str:
"""Return current time (system timezone) in `hh:mm:ss` format."""
return now_datetime().strftime(TIME_FORMAT)
@typing.overload
def get_first_day(dt, d_years=0, d_months=0, as_str: Literal[False] = False) -> datetime.date:
...
@typing.overload
def get_first_day(dt, d_years=0, d_months=0, as_str: Literal[True] = False) -> str:
...
# TODO: first arg
def get_first_day(dt, d_years: int = 0, d_months: int = 0, as_str: bool = False) -> str | datetime.date:
"""Return the first day of the month for the date specified by date object.
Also, add `d_years` and `d_months` if specified.
"""
dt = getdate(dt)
# d_years, d_months are "deltas" to apply to dt
overflow_years, month = divmod(dt.month + d_months - 1, 12)
year = dt.year + d_years + overflow_years
return (
datetime.date(year, month + 1, 1).strftime(DATE_FORMAT)
if as_str
else datetime.date(year, month + 1, 1)
)
@typing.overload
def get_quarter_start(dt: DateTimeLikeObject | None = None, as_str: Literal[False] = False) -> datetime.date:
...
@typing.overload
def get_quarter_start(dt: DateTimeLikeObject | None = None, as_str: Literal[True] = False) -> str:
...
def get_quarter_start(dt: DateTimeLikeObject | None = None, as_str: bool = False) -> str | datetime.date:
"""Return the start date of the quarter for the given datetime like object (`dt`).
If `dt` is None, the current quarter start date is returned.
"""
date = getdate(dt)
quarter = (date.month - 1) // 3 + 1
first_date_of_quarter = datetime.date(date.year, ((quarter - 1) * 3) + 1, 1)
return first_date_of_quarter.strftime(DATE_FORMAT) if as_str else first_date_of_quarter
@typing.overload
def get_first_day_of_week(dt: DateTimeLikeObject, as_str: Literal[False] = False) -> datetime.date:
...
@typing.overload
def get_first_day_of_week(dt: DateTimeLikeObject, as_str: Literal[True] = False) -> str:
...
def get_first_day_of_week(dt: DateTimeLikeObject, as_str=False) -> datetime.date | str:
"""Return the first day of the week (as per System Settings or Sunday by default) for the given datetime like object (`dt`).
If `as_str` is True, the first day of the week is returned as a string in `yyyy-mm-dd` format.
"""
dt = getdate(dt)
date = dt - datetime.timedelta(days=get_week_start_offset_days(dt))
return date.strftime(DATE_FORMAT) if as_str else date
def get_week_start_offset_days(dt):
current_day_index = get_normalized_weekday_index(dt)
start_of_week_index = get_start_of_week_index()
if current_day_index >= start_of_week_index:
return current_day_index - start_of_week_index
else:
return 7 - (start_of_week_index - current_day_index)
def get_normalized_weekday_index(dt):
# starts Sunday with 0
return (dt.weekday() + 1) % 7
@typing.overload
def get_year_start(dt: DateTimeLikeObject, as_str: Literal[False] = False) -> datetime.date:
...
@typing.overload
def get_year_start(dt: DateTimeLikeObject, as_str: Literal[True] = False) -> str:
...
def get_year_start(dt: DateTimeLikeObject, as_str=False) -> str | datetime.date:
"""Return the start date of the year for the given date (`dt`)."""
dt = getdate(dt)
date = datetime.date(dt.year, 1, 1)
return date.strftime(DATE_FORMAT) if as_str else date
@typing.overload
def get_last_day_of_week(dt: DateTimeLikeObject, as_str: Literal[False] = False) -> datetime.date:
...
@typing.overload
def get_last_day_of_week(dt: DateTimeLikeObject, as_str: Literal[True] = False) -> str:
...
def get_last_day_of_week(dt: DateTimeLikeObject, as_str=False) -> datetime.date | str:
"""Return the last day of the week (first day is taken from System Settings or Sunday by default) for the given datetime like object (`dt`).
If `as_str` is True, the last day of the week is returned as a string in `yyyy-mm-dd` format.
"""
dt = get_first_day_of_week(dt)
date = dt + datetime.timedelta(days=6)
return date.strftime(DATE_FORMAT) if as_str else date
def get_last_day(dt):
"""Return last day of the month using:
`get_first_day(dt, 0, 1) + datetime.timedelta(-1)`
"""
return get_first_day(dt, 0, 1) + datetime.timedelta(-1)
def is_last_day_of_the_month(dt):
last_day_of_the_month = get_last_day(dt)
return getdate(dt) == getdate(last_day_of_the_month)
@typing.overload
def get_quarter_ending(dt: DateTimeLikeObject | None = None, as_str: Literal[False] = False) -> datetime.date:
...
@typing.overload
def get_quarter_ending(dt: DateTimeLikeObject | None = None, as_str: Literal[True] = False) -> str:
...
def get_quarter_ending(date: DateTimeLikeObject | None = None, as_str=False) -> str | datetime.date:
"""Return the end date of the quarter for the given datetime like object (`date`).
If `date` is None, the current quarter end date is returned.
If `as_str` is True, the end date of the quarter is returned as a string in `yyyy-mm-dd` format.
"""
date = getdate(date)
# find the earliest quarter ending date that is after
# the given date
for month in (3, 6, 9, 12):
quarter_end_month = getdate(f"{date.year}-{month}-01")
quarter_end_date = getdate(get_last_day(quarter_end_month))
if date <= quarter_end_date:
date = quarter_end_date
break
return date.strftime(DATE_FORMAT) if as_str else date
@typing.overload
def get_year_ending(dt: DateTimeLikeObject | None = None, as_str: Literal[False] = False) -> datetime.date:
...
@typing.overload
def get_year_ending(dt: DateTimeLikeObject | None = None, as_str: Literal[True] = False) -> str:
...
def get_year_ending(date: DateTimeLikeObject | None = None, as_str=False) -> datetime.date | str:
"""Return the end date of the year for the given datetime like object (`date`).
If `date` is None, the current year end date is returned.
If `as_str` is True, the end date of the year is returned as a string in `yyyy-mm-dd` format.
"""
date = getdate(date)
next_year_start = datetime.date(date.year + 1, 1, 1)
year_ending = add_to_date(next_year_start, days=-1)
return year_ending.strftime(DATE_FORMAT) if as_str else year_ending
def get_time(
time_str: str | datetime.datetime | datetime.time | datetime.timedelta,
) -> datetime.time:
"""Return a `datetime.time` object for the given `time_str`.
If the given argument is already a `datetime.time` object, it is returned as is."""
if isinstance(time_str, datetime.datetime):
return time_str.time()
elif isinstance(time_str, datetime.time):
return time_str
elif isinstance(time_str, datetime.timedelta):
return (datetime.datetime.min + time_str).time()
try:
return parser.parse(time_str).time()
except ParserError as e:
if "day" in e.args[1] or "hour must be in" in e.args[0]:
return (datetime.datetime.min + parse_timedelta(time_str)).time()
raise e
def get_datetime_str(datetime_obj: DateTimeLikeObject) -> str:
"""Return the given datetime like object (datetime.date, datetime.datetime, string) as a string in `yyyy-mm-dd hh:mm:ss` format."""
if isinstance(datetime_obj, str):
datetime_obj = get_datetime(datetime_obj)
return datetime_obj.strftime(DATETIME_FORMAT)
def get_date_str(date_obj: DateTimeLikeObject) -> str:
"""Return the given datetime like object (datetime.date, datetime.datetime, string) as a string in `yyyy-mm-dd` format."""
if isinstance(date_obj, str):
date_obj = get_datetime(date_obj)
return date_obj.strftime(DATE_FORMAT)
def get_time_str(timedelta_obj: datetime.timedelta | str) -> str:
"""Return the given timedelta object as a string in `hh:mm:ss` format."""
if isinstance(timedelta_obj, str):
timedelta_obj = to_timedelta(timedelta_obj)
hours, remainder = divmod(timedelta_obj.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
return f"{hours}:{minutes}:{seconds}"
def get_user_date_format() -> str:
"""Get the current user date format. The result will be cached."""
if getattr(frappe.local, "user_date_format", None) is None:
frappe.local.user_date_format = frappe.db.get_default("date_format")
return frappe.local.user_date_format or "yyyy-mm-dd"
get_user_format = get_user_date_format # for backwards compatibility
def get_user_time_format() -> str:
"""Get the current user time format. The result will be cached."""
if getattr(frappe.local, "user_time_format", None) is None:
frappe.local.user_time_format = frappe.db.get_default("time_format")
return frappe.local.user_time_format or "HH:mm:ss"
def format_date(string_date=None, format_string: str | None = None, parse_day_first: bool = False) -> str:
"""Convert the given string date to :data:`user_date_format`.
User format specified in defaults
Examples:
* dd-mm-yyyy
* mm-dd-yyyy
* dd/mm/yyyy
"""
import babel.dates
from babel.core import UnknownLocaleError
if not string_date:
return ""
date = getdate(string_date, parse_day_first)
if not format_string:
format_string = get_user_date_format()
format_string = format_string.replace("mm", "MM").replace("Y", "y")
try:
formatted_date = babel.dates.format_date(
date, format_string, locale=(frappe.local.lang or "").replace("-", "_")
)
except UnknownLocaleError:
format_string = format_string.replace("MM", "%m").replace("dd", "%d").replace("yyyy", "%Y")
formatted_date = date.strftime(format_string)
return formatted_date
formatdate = format_date # For backwards compatibility
def format_time(time_string=None, format_string: str | None = None) -> str:
"""Convert the given string time to :data:`user_time_format`.
User format specified in defaults
Examples:
* HH:mm:ss
* HH:mm
"""
import babel.dates
from babel.core import UnknownLocaleError
if not time_string:
return ""
time_ = get_time(time_string)
if not format_string:
format_string = get_user_time_format()
try:
formatted_time = babel.dates.format_time(
time_, format_string, locale=(frappe.local.lang or "").replace("-", "_")
)
except UnknownLocaleError:
formatted_time = time_.strftime("%H:%M:%S")
return formatted_time
def format_datetime(datetime_string: DateTimeLikeObject, format_string: str | None = None) -> str:
"""Convert the given string time to :data:`user_datetime_format`
User format specified in defaults
Examples:
* dd-mm-yyyy HH:mm:ss
* mm-dd-yyyy HH:mm
"""
import babel.dates
from babel.core import UnknownLocaleError
if not datetime_string:
return
datetime = get_datetime(datetime_string)
if not format_string:
format_string = get_user_date_format().replace("mm", "MM") + " " + get_user_time_format()
try:
formatted_datetime = babel.dates.format_datetime(
datetime, format_string, locale=(frappe.local.lang or "").replace("-", "_")
)
except UnknownLocaleError:
formatted_datetime = datetime.strftime("%Y-%m-%d %H:%M:%S")
return formatted_datetime
def format_duration(seconds, hide_days=False):
"""Convert the given duration value in float(seconds) to duration format.
example: convert 12885 to '3h 34m 45s' where 12885 = seconds in float
"""
seconds = cint(seconds)
total_duration = {
"days": math.floor(seconds / (3600 * 24)),
"hours": math.floor(seconds % (3600 * 24) / 3600),
"minutes": math.floor(seconds % 3600 / 60),
"seconds": math.floor(seconds % 60),
}
if hide_days:
total_duration["hours"] = math.floor(seconds / 3600)
total_duration["days"] = 0
duration = ""
if total_duration:
if total_duration.get("days"):
duration += str(total_duration.get("days")) + "d"
if total_duration.get("hours"):
duration += " " if len(duration) else ""
duration += str(total_duration.get("hours")) + "h"
if total_duration.get("minutes"):
duration += " " if len(duration) else ""
duration += str(total_duration.get("minutes")) + "m"
if total_duration.get("seconds"):
duration += " " if len(duration) else ""
duration += str(total_duration.get("seconds")) + "s"
return duration
def duration_to_seconds(duration):
"""Convert the given duration formatted value to duration value in seconds.
example: convert '3h 34m 45s' to 12885 (value in seconds)
"""
validate_duration_format(duration)
value = 0
if "d" in duration:
val = duration.split("d")
days = val[0]
value += cint(days) * 24 * 60 * 60
duration = val[1]
if "h" in duration:
val = duration.split("h")
hours = val[0]
value += cint(hours) * 60 * 60
duration = val[1]
if "m" in duration:
val = duration.split("m")
mins = val[0]
value += cint(mins) * 60
duration = val[1]
if "s" in duration:
val = duration.split("s")
secs = val[0]
value += cint(secs)
return value
def validate_duration_format(duration):
if not DURATION_PATTERN.match(duration):
frappe.throw(
frappe._("Value {0} must be in the valid duration format: d h m s").format(frappe.bold(duration))
)
def get_weekdays() -> list[str]:
"""Return a list of weekday names.
Return value: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
"""
return ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
def get_weekday(datetime: DateTimeLikeObject | None = None) -> str:
"""Return the weekday name (e.g. 'Sunday') for the given datetime like object (datetime.date, datetime.datetime, string).
If `datetime` argument is not provided, the current weekday name is returned.
"""
if not datetime:
datetime = now_datetime()
if isinstance(datetime, str):
datetime = get_datetime(datetime)
weekdays = get_weekdays()
return weekdays[datetime.weekday()]
def get_timespan_date_range(
timespan: TimespanOptions,
) -> tuple[datetime.datetime, datetime.datetime] | None:
"""Return the date range (start_date, end_date) tuple for the given timespan."""
today = getdate()
match timespan:
case "last week":
return (
get_first_day_of_week(add_to_date(today, days=-7)),
get_last_day_of_week(add_to_date(today, days=-7)),
)
case "last month":
return (
get_first_day(add_to_date(today, months=-1)),
get_last_day(add_to_date(today, months=-1)),
)
case "last quarter":
return (
get_quarter_start(add_to_date(today, months=-3)),
get_quarter_ending(add_to_date(today, months=-3)),
)
case "last 6 months":
return (
get_quarter_start(add_to_date(today, months=-6)),
get_quarter_ending(add_to_date(today, months=-3)),
)
case "last year":
return (
get_year_start(add_to_date(today, years=-1)),
get_year_ending(add_to_date(today, years=-1)),
)
case "yesterday":
return (add_to_date(today, days=-1),) * 2
case "today":
return (today, today)
case "tomorrow":
return (add_to_date(today, days=1),) * 2
case "this week":
return (get_first_day_of_week(today), get_last_day_of_week(today))
case "this month":
return (get_first_day(today), get_last_day(today))
case "this quarter":
return (get_quarter_start(today), get_quarter_ending(today))
case "this year":
return (get_year_start(today), get_year_ending(today))
case "next week":
return (
get_first_day_of_week(add_to_date(today, days=7)),
get_last_day_of_week(add_to_date(today, days=7)),
)
case "next month":
return (
get_first_day(add_to_date(today, months=1)),
get_last_day(add_to_date(today, months=1)),
)
case "next quarter":
return (
get_quarter_start(add_to_date(today, months=3)),
get_quarter_ending(add_to_date(today, months=3)),
)
case "next 6 months":
return (
get_quarter_start(add_to_date(today, months=3)),
get_quarter_ending(add_to_date(today, months=6)),
)
case "next year":
return (
get_year_start(add_to_date(today, years=1)),
get_year_ending(add_to_date(today, years=1)),
)
case _:
return
def global_date_format(date: DateTimeLikeObject, format="long") -> str:
"""Return localized date in the form of 'January 1, 2012'."""
import babel.dates
date = getdate(date)
return babel.dates.format_date(date, locale=(frappe.local.lang or "en").replace("-", "_"), format=format)
def has_common(l1: typing.Hashable, l2: typing.Hashable) -> bool:
"""Return truthy value if there are common elements in lists l1 and l2."""
return set(l1) & set(l2)
def cast_fieldtype(fieldtype, value, show_warning=True):
if show_warning:
message = (
"Function `frappe.utils.data.cast_fieldtype` has been deprecated in favour"
" of `frappe.utils.data.cast`. Use the newer util for safer type casting."
)
secho(message, fg="yellow")
if fieldtype in ("Currency", "Float", "Percent"):
value = flt(value)
elif fieldtype in ("Int", "Check"):
value = cint(value)
elif fieldtype in (
"Data",
"Text",
"Small Text",
"Long Text",
"Text Editor",
"Select",
"Link",
"Dynamic Link",
):