Python notes - date and time

From Helpful
Jump to: navigation, search
Various things have their own pages, see Category:Python. Some of the pages that collect various practical notes include:


Some code I've copy-pasted more than once:

from seconds-since-unix-epoch

# to '''datetime object'''
# int or float

from elapsed seconds

# to timedelta

from timedelta

### to time difference in seconds
# py>=2.7 added
# py2.6 and earlier:

from datetime

WARNING: discards timezone.

# to ISO8601-like string
### to unix timestamp (float) 
# some variations. If you care about microseconds:

from seconds-since-epoch (a.k.a. unix time, a.k.a. "what time.time() gives")

# to datetime
# to ISO8601 style string

From ISO8601 string

### to datetime
# simplest, but you have to install/include it
# quick and dirty independent hack
''' If you want to deal with timezones correctly, 
        or want to deal with the compact format at all,
        then you probably want to use dateutil instead. '''
    d, t = s.split('T''-''-''Z''Z''+''+''.'# also chops off the above. Separate because I could add fractional-sec handling later                                                                                         

from standardish strings

dateutil is a nice library for structured-but-not-quite-as-standardized strings (and various date-based logic you may not want to do yourself).

You probably want to just use dateutil.parser.parse()

For example:

span style="color: #483d9b;">'2015-06-26 23:00:41'"Thu Sep 25 2003"

It seems to match on known patterns so will will work on many commonish/standardish things.

It doesn't like seeing parts it doesn't understand, though will be more permissive with fuzzy=True (e.g. it groks apache's date format only with fuzziness, apparently because of the unexpected : between date and time)

On ambiguous dates like 02-04-2012 you may have to guide it, see e.g. [1]

from apache log time

Apache uses date-time-with-timezone format like:

29/Nov/2013:14:21:20 +0100

dateutil.parser.parse with fuzzy=True will deal.

You can do with with a dozen lines of string manipulation, which may be slightly faster(verify) (TODO: add that)


See also: