Python parse date format

Custom date format parsing in python

ValueError: time data «(‘2016-04-15T12:24:20.707Z’,)» does not match format ‘%Y-%m-%dT%H:%M:%S.%fZ’ is the error I am getting when I try the same thing, maybe because I am retrieving it from the database and not hardcoding it.

You have to specify the format as «%Y-%m-%dT%H:%M:%S.%fZ» while conversion

In [11]: from datetime import datetime In [12]: out_format = "%Y-%m-%d" In [13]: input_format="%Y-%m-%dT%H:%M:%S.%fZ" In [14]: date_time_obj = datetime.strptime(time,input_format) In [15]: date_time_obj Out[15]: datetime.datetime(2016, 4, 15, 12, 24, 20, 707000) In [16]: date_time_str = date_time_obj.strftime(out_format) In [17]: date_time_str Out[17]: '2016-04-15' 
import dateutil.parser from datetime import datetime dt = dateutil.parser.parse('2016-04-15T12:24:20.707Z') 

This seems to be working alright:

import dateparser dateparser.parse('2016-04-15T12:24:20.707Z') > datetime.datetime(2016, 4, 15, 12, 24, 20, 707000, tzinfo=) 

It works fine, when I hardcode the date as the parameter to parse, since I am retrieving the date from mysql raise ValueError(«Unknown string format:», timestr) ValueError: (‘Unknown string format:’, «(‘2016-04-15T12:24:20.707Z’,)»)

Well, it looks like the datestring from your DB is a tuple . you might need to remove the double quotes and brackets. Alternatively you could try to eval the string and access the first element in the tuple which should be the datestring. Btw: this is exactly why questions should contain a minimal-complete example since this whole thread is now a instance of an XY-Problem.

Probably iso8601 package is what you need

You may try this way if you need something on the fly:

This returns the current datetime in UTC, as a datetime object then immediately converts it to your preferred custom format.

from datetime import datetime, timezone from time import strftime # Get UTC Time datetime object and convert it to your preferred format. print(f"Regular : < datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S') >") # Regular : 2022-06-04 23:08:27 print(f"Log Format: < datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S') >") # Log Format: 20220604_230827 print(f"YMD Format: < datetime.now(timezone.utc).strftime('%Y-%m-%d') >") # YMD Format: 2022-06-04 print(f"Time Format: < datetime.now(timezone.utc).strftime('%H:%M:%S') >") # Time Format: 23:08:27 # Without the f'String' print(datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')) # Regular : 2022-06-04 23:08:27 print(datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')) # Log Format: 20220604_230827 print(datetime.now(timezone.utc).strftime('%Y-%m-%d')) # YMD Format: 2022-06-04 print(datetime.now(timezone.utc).strftime('%H%M%S')) # Time Format: 23:08:27 # Details: # Get current DateTime in UTC datetime.now(timezone.utc) # datetime.datetime(2022, 6, 4, 23, 13, 27, 498392, tzinfo=datetime.timezone.utc) type(datetime.now(timezone.utc)) # # Use the strftime on the datetime object directly datetime(2022, 6, 4, 23, 13, 27, 498392, tzinfo=timezone.utc).strftime('%Y-%m-%d %H:%M:%S') # '2022-06-04 23:13:27' type(datetime(2022, 6, 4, 23, 13, 27, 498392, tzinfo=timezone.utc).strftime('%Y-%m-%d %H:%M:%S')) #

Источник

parser¶

This module offers a generic date/time string parser which is able to parse most known formats to represent a date and/or time.

Читайте также:  Import команда в питоне

This module attempts to be forgiving with regards to unlikely input formats, returning a datetime object even for dates which are ambiguous. If an element of a date/time stamp is omitted, the following rules are applied:

  • If AM or PM is left unspecified, a 24-hour clock is assumed, however, an hour on a 12-hour clock ( 0 must be specified if AM or PM is specified.
  • If a time zone is omitted, a timezone-naive datetime is returned.

If any other elements are missing, they are taken from the datetime.datetime object passed to the parameter default . If this results in a day number exceeding the valid number of days per month, the value falls back to the end of the month.

Additional resources about date/time string formats can be found below:

Functions¶

Parse a string in one of the supported formats, using the parserinfo parameters.

  • timestr – A string containing a date/time stamp.
  • parserinfo – A parserinfo object containing parameters for the parser. If None , the default arguments to the parserinfo constructor are used.

The **kwargs parameter takes the following keyword arguments:

  • default – The default datetime object, if this is a datetime object and not None , elements specified in timestr replace elements in the default object.
  • ignoretz – If set True , time zones in parsed strings are ignored and a naive datetime object is returned.
  • tzinfos – Additional time zone names / aliases which may be present in the string. This argument maps time zone names (and optionally offsets from those time zones) to time zones. This parameter can be a dictionary with timezone aliases mapping time zone names to time zones or a function taking two parameters ( tzname and tzoffset ) and returning a time zone. The timezones to which the names are mapped can be an integer offset from UTC in seconds or a tzinfo object.
 >>> from dateutil.parser import parse >>> from dateutil.tz import gettz >>> tzinfos =  >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) 
>>> from dateutil.parser import parse >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) 

Returns a datetime.datetime object or, if the fuzzy_with_tokens option is True , returns a tuple, the first element being a datetime.datetime object, the second a tuple containing the fuzzy tokens.

  • ParserError – Raised for invalid or unknown string formats, if the provided tzinfo is not in a valid format, or if an invalid date would be created.
  • OverflowError – Raised if the parsed date exceeds the largest valid C integer on your system.

Parse an ISO-8601 datetime string into a datetime.datetime .

An ISO-8601 datetime string consists of a date portion, followed optionally by a time portion — the date and time portions are separated by a single character separator, which is T in the official standard. Incomplete date formats (such as YYYY-MM ) may not be combined with a time portion.

Supported date formats are:

  • YYYY-Www or YYYYWww — ISO week (day defaults to 0)
  • YYYY-Www-D or YYYYWwwD — ISO week and day

The ISO week and day numbering follows the same logic as datetime.date.isocalendar() .

Supported time formats are:

  • hh
  • hh:mm or hhmm
  • hh:mm:ss or hhmmss
  • hh:mm:ss.ssssss (Up to 6 sub-second digits)

Midnight is a special case for hh , as the standard supports both 00:00 and 24:00 as a representation. The decimal separator can be either a dot or a comma.

Support for fractional components other than seconds is part of the ISO-8601 standard, but is not currently implemented in this parser.

Supported time zone offset formats are:

Offsets will be represented as dateutil.tz.tzoffset objects, with the exception of UTC, which will be represented as dateutil.tz.tzutc . Time zone offsets equivalent to UTC (such as +00:00 ) will also be represented as dateutil.tz.tzutc .

Parameters: dt_str – A string or stream containing only an ISO-8601 datetime string
Returns: Returns a datetime.datetime representing the string. Unspecified components default to their lowest value.

As of version 2.7.0, the strictness of the parser should not be considered a stable part of the contract. Any valid ISO-8601 string that parses correctly with the default settings will continue to parse correctly in future versions, but invalid strings that currently fail (e.g. 2017-01-01T00:00+00:00:00 ) are not guaranteed to continue failing in future versions if they encode a valid date.

Classes¶

Class which handles what inputs are accepted. Subclass this to customize the language and acceptable values for each parameter.

  • dayfirst – Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day ( True ) or month ( False ). If yearfirst is set to True , this distinguishes between YDM and YMD. Default is False .
  • yearfirst – Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If True , the first number is taken to be the year, otherwise the last number is taken to be the year. Default is False .

Converts two-digit years to year within [-50, 49] range of self._year (current local time)

hms ( name ) [source] ¶ jump ( name ) [source] ¶ month ( name ) [source] ¶ pertain ( name ) [source] ¶ tzoffset ( name ) [source] ¶ utczone ( name ) [source] ¶ validate ( res ) [source] ¶ weekday ( name ) [source] ¶

Warnings and Exceptions¶

Exception subclass used for any failure to parse a datetime string.

This is a subclass of ValueError , and should be raised any time earlier versions of dateutil would have raised ValueError .

Raised when the parser finds a timezone it cannot parse into a tzinfo.

© Copyright 2019, dateutil Revision 6b035517 .

Источник

Оцените статью