Datetime field. Uses the python-dateutil library if available alternatively use time.strptime to parse the dates. Note: python-dateutil's parser is fully featured and when installed you can utilise it to convert varying types of date formats into valid python datetime objects.
| 517 | |
| 518 | |
| 519 | class DateTimeField(BaseField): |
| 520 | """Datetime field. |
| 521 | |
| 522 | Uses the python-dateutil library if available alternatively use time.strptime |
| 523 | to parse the dates. Note: python-dateutil's parser is fully featured and when |
| 524 | installed you can utilise it to convert varying types of date formats into valid |
| 525 | python datetime objects. |
| 526 | |
| 527 | Note: To default the field to the current datetime, use: DateTimeField(default=datetime.utcnow) |
| 528 | |
| 529 | Note: Microseconds are rounded to the nearest millisecond. |
| 530 | Pre UTC microsecond support is effectively broken. |
| 531 | Use :class:`~mongoengine.fields.ComplexDateTimeField` if you |
| 532 | need accurate microsecond support. |
| 533 | """ |
| 534 | |
| 535 | def validate(self, value): |
| 536 | new_value = self.to_mongo(value) |
| 537 | if not isinstance(new_value, (datetime.datetime, datetime.date)): |
| 538 | self.error('cannot parse date "%s"' % value) |
| 539 | |
| 540 | def to_mongo(self, value): |
| 541 | if value is None: |
| 542 | return value |
| 543 | if isinstance(value, datetime.datetime): |
| 544 | return value |
| 545 | if isinstance(value, datetime.date): |
| 546 | return datetime.datetime(value.year, value.month, value.day) |
| 547 | if callable(value): |
| 548 | return value() |
| 549 | |
| 550 | if isinstance(value, str): |
| 551 | return self._parse_datetime(value) |
| 552 | else: |
| 553 | return None |
| 554 | |
| 555 | @staticmethod |
| 556 | def _parse_datetime(value): |
| 557 | # Attempt to parse a datetime from a string |
| 558 | value = value.strip() |
| 559 | if not value: |
| 560 | return None |
| 561 | |
| 562 | if dateutil: |
| 563 | try: |
| 564 | return dateutil.parser.parse(value) |
| 565 | except (TypeError, ValueError, OverflowError): |
| 566 | return None |
| 567 | |
| 568 | # split usecs, because they are not recognized by strptime. |
| 569 | if "." in value: |
| 570 | try: |
| 571 | value, usecs = value.split(".") |
| 572 | usecs = int(usecs) |
| 573 | except ValueError: |
| 574 | return None |
| 575 | else: |
| 576 | usecs = 0 |
no outgoing calls
no test coverage detected