How to parse datetime with Z letter with number after semicolon [duplicate] - python

This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 1 year ago.
I'm parsing timestamp of event in a log record – 2020-08-09T03:37:33.358874554Z.
It looks strange to me and I don't know how correct is it. I don'think that 358874554 describe.
I'm trying to parse this example from Python 3.7 like this:
dt.datetime.strptime('2020-08-09T03:37:33.358874554Z', "%Y-%m-%dT%H:%M:%S.%fZ")
It generates an error:
ValueError: time data '2020-08-09T03:37:33.358874554Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'
How to parse such a datetime correctly?
Is this datetime example in log is correct (in terms of ISO or anything)?

You can use the dateutil.parser
Like this:
>>>>import dateutil.parser as p
>>>>p.parse('2020-08-09T03:37:33.358874554Z')
datetime.datetime(2020, 8, 9, 3, 37, 33, 358874, tzinfo=tzutc())

You should use dateutil module as an alternative:
$ pip install python-dateutil
>>> import dateutil.parser
>>> dateutil.parser.isoparse('2020-08-09T03:37:33.358874554Z')
datetime.datetime(2020, 8, 9, 3, 37, 33, 358874, tzinfo=tzutc())

Related

Subtract 3 months from datetime.now() [duplicate]

This question already has answers here:
How do I calculate the date six months from the current date using the datetime Python module?
(47 answers)
Closed 3 years ago.
How do I remove 3 months from the date? tried to use relativedelta, but I don't have the lib, so is there another way?
from datetime import datetime
now = datetime.now()
print("timestamp =", now)
You can use:
import datetime
a = datetime.datetime.now()
b = a - datetime.timedelta(weeks=12)
Note that you cannot give months as inputs, but weeks and days, and smaller
Perhaps, subtracting with datetime.timedelta can help you estimate the date:
import datetime
datetime.datetime(2019,5,31) - datetime.timedelta(3*365.25/12)
This result is not completely accurate, as it does not account for the leap years in the usual way, however for less precise calculations within a year should suffice. If you need accuracy you will need to use the method below.
For dateutil.relativedelta, you need to first install the module with pip install python-dateutil, and then use it in the following way:
import datetime
from dateutil.relativedelta import relativedelta
datetime.datetime(2019,5,31) - relativedelta(months=3)
If you want to perform complex operations on datetime objects, I can only recommend you to use the library arrow that will handle all the edge cases for you.
The documentation of this library is available here: https://arrow.readthedocs.io/en/latest/
For instance in your case:
>>> import arrow
>>> a = arrow.utcnow()
>>> a
<Arrow [2019-11-20T13:03:52.518238+00:00]>
>>> a.datetime
datetime.datetime(2019, 11, 20, 13, 3, 52, 518238, tzinfo=tzutc())
>>> b = a.shift(months=-3)
>>> b
<Arrow [2019-08-20T13:03:52.518238+00:00]>
>>> b.datetime
datetime.datetime(2019, 8, 20, 13, 3, 52, 518238, tzinfo=tzutc())

Convert Snort string to Python timestamp

I'm using Snort, which generates timestamps in MM-DD/time format, such as:
06/18-19:31:05.688344
I want to convert this to a Python timestamp, including the current year. What's the most pythonic way?
Use the datetime module's strptime function.
>>> import datetime
>>> datetime.datetime.strptime(str(datetime.datetime.now().year) +
... '/' + '06/18-19:31:05.688344', '%Y/%m/%d-%H:%M:%S.%f')
datetime.datetime(2015, 6, 18, 19, 31, 5, 688344)
Check out snorts configuration. In the output section you can setup "seconds" as an output field. This is the timestamp in unix format which is better to work with. If u still need to convert it :
datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')

Converting AM/PM Time to epoch [duplicate]

This question already has answers here:
How can I account for period (AM/PM) using strftime?
(5 answers)
Closed 7 years ago.
I'm trying to convert a string date to epoch, but it doesn't seem to pick up the am or pm. The time always defaults to am.
I've tried this:
dt = '2015-05-04 5:55PM'
pattern = '%Y-%m-%d %H:%M%p'
epochDate = int(time.mktime(time.strptime(dt, pattern)))
print epochDate
# Result
1430684700
# Checking output
datetime.datetime.fromtimestamp(1430684700).strftime('%Y-%m-%d %H:%M:%S%p')
# Doesn't show PM
'2015-05-04 05:55:00AM'
I'm not sure what I've done wrong here?
You should use the python-dateutil library:
>>> import dateutil.parser
>>> dateutil.parser.parse('2015-05-04 5:55PM')
datetime.datetime(2015, 5, 4, 17, 55)
>>> dateutil.parser.parse('2015-05-04 5:55AM')
datetime.datetime(2015, 5, 4, 5, 55)

Convert odd timestamp with offset to UNIX time in Python [duplicate]

This question already has an answer here:
Converting string with UTC offset to a datetime object [duplicate]
(1 answer)
Closed 9 years ago.
I have a timestamp string from a web log that looks like this:
10/Jun/2005:05:59:05 -0500
It like to convert it to a UNIX timestamp.
A datetime can be converted with time.mktime(datetime.timetuple())
According to the datetime docs, datetime.strptime() should convert it to a datetime:
from datetime import datetime
datetime.strptime("10/Jun/2005:05:59:05 -0500","%d/%b/%Y:%H:%M:%S %z")
At least on with Python 2.7.2 on my Mac, this results in
ValueError: 'z' is a bad directive in format '%d/%b/%Y:%H:%M:%S %z'
After reading many questions on SO about that error, I decided to try python-dateutil:
from dateutil import parser
parser.parse("10/Jun/2005:05:59:05 -0500")
That didn't work either:
ValueError: unknown string format
Now what?
You can use dateutils to make the converstion, you will need two steps:
>>> import calendar
>>> from dateutil.parser import parse
>>> d = parse('10/Jun/2005:05:59:05 -0500', fuzzy=True)
This will create a datetime object
>>> d
datetime.datetime(2005, 6, 10, 5, 59, 5, tzinfo=tzoffset(None, -18000))
And to convert it to UNIX timestamp:
>>> ts = calendar.timegm(d.utctimetuple())
>>> print ts
1118401145

how to convert this date string to "2011-02-15T12:00+00:00" python datetime object

how to convert this date string to "2011-02-15T12:00+00:00" python datetime object in following format "Wed, Feb, 15, 2011 15:00" ?
It seems ISO 8601 format. Try using iso8601 package — you can install it through pip or easy_install.
Many file formats and standards use the ISO 8601 date format (e.g. 2007-01-14T20:34:22+00:00) to store dates in a neutral, unambiguous manner. This simple module parses the most common forms encountered and returns datetime objects.
>>> import iso8601
>>> iso8601.parse_date("2007-06-20T12:34:40+03:00")
datetime.datetime(2007, 6, 20, 12, 34, 40, tzinfo=<FixedOffset '+03:00'>)
>>> iso8601.parse_date("2007-06-20T12:34:40Z")
datetime.datetime(2007, 6, 20, 12, 34, 40, tzinfo=<iso8601.iso8601.Utc object at 0x100ebf0>)
Considering that you know the exact format of the date string, you can parse it to extract each value.
I'm not sure what the +00:00 part means, so I'll ignore that for now.
str="2011-02-15T12:00+00:00"
year=int(str[:4])
month=int(str[5:7])
day=int(str[8:10])
hour=int(str[11:13])
minute=int(str[14:16])
date = datetime(year,month,day,hour,minute)

Categories

Resources