Parsing timestamp with Python2.4 - python

I want to parse a timestamp from a log file that has been written via
datetime.datetime.now().strftime('%Y%m%d%H%M%S')
and then compute the number of seconds that have passed since this timestamp.
I know I could do it with datetime.datetime.strptime to get back a datetime object and then compute a timedelta. Problem is, the strptime function has been introduced with Python 2.5 and I'm using Python2.4.4 (an upgrade is not possible in my context).
Any easy way to do this?

>>> ts = time.mktime(time.strptime('20040412234551', '%Y%m%d%H%M%S'))
>>> ts
1081809951.0
>>> datetime.datetime.fromtimestamp(ts)
datetime.datetime(2004, 4, 12, 23, 45, 51)

now = datetime.datetime.now()
then = datetime.datetime(*time.strptime('20080227034510' ,'%Y%m%d%H%M%S')[0:6])
difference = now - then

There is a strptime function in the time module in python 2.4 already. You'd have to convert that to a datetime object for example via the detour of the unix timestamp, don't know if there's a better way.

There's also mx.DateTime which is now free to use and it quite a bit easier to deal with and more flexible than Python's built in datetime module for well just about everything. Works in python 2.3+ No * and [0:6] shenanigans required.
Egenix Download
>>> import mx.DateTime as dt
>>> then = dt.DateTimeFrom(dt.strptime('20040412234551', '%Y%m%d%H%M%S'))
>>> delta = dt.now() - then
>>> delta
<DateTimeDelta object for '2247:13:09:22.31' at 2ab37d666b58>
>>> delta.hours
53941.156198977762
>>> delta.days
2247.5481749574069

Related

Python: How to display date time in following format (2018-06-25T07:17:17.000Z)?

I want to display the datetime in the following format using python:
2018-06-25T07:17:17.000Z
I am trying to convert using strftime:
datetime.datetime.now().strftime("%Y-%m-%dTH:M:SZ")
but it seems that doesn't work.
What i am missing?
you can use
import datetime
datetime.datetime.today().isoformat()
2018-06-25T07:17:17.000Z
This format is called ISO format, after standard ISO 8601. The datetime object has a isoformat method to output this form.
strftime("%Y-%m-%dTH:M:SZ")
You seem to have forgotten some % before the H, M, and S. Try strftime("%Y-%m-%dT%H:%M:%SZ").
but it seems that doesn't work.
Generally it works better if you specify exactly what doesn't work, or what you expect and how the reality differs from your expectation.
You can use following formating for date conversion.
>>> import datetime
>>> today_date = datetime.datetime.now()
>>> today_date.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
'2018-06-25T15:50:18.313620Z'
Please let me know,if this is the one you needed.

How to convert string date to a epoch timestamp in python

I have a string date as 2015-03-25T00:00:00Z. How do I convert it to a unix epoch1426636800000.0
Are there any libraries in python to do that.
Using time, for example.
So first you need to convert the string to time object (or you can use datetime alternatively as halex mentioned) and then get the seconds since epoch.
>>> import time
>>> time.mktime(time.strptime('2015-03-25T00:00:00Z', '%Y-%m-%dT%H:%M:%SZ'))
1427241600.0
time.strptime(string[, format])
import time
print time.strptime("2015-03-25T00:00:00Z","%Y-%m-%dT%H:%M:%SZ")
If you have Python 3.3 or newer you can use the datetime module:
>>> import datetime
>>> datetime.datetime.strptime("2015-03-25T00:00:00Z", "%Y-%m-%dT%H:%M:%SZ").timestamp()
1427238000.0
You can use easy_date to make it easy:
import date_converter
timestamp = date_converter.string_to_timestamp("2015-03-25T00:00:00Z", "%Y-%m-%dT%H:%M:%SZ")

Convert datetime to local python

I have been reading quite some time answers and couldn't really drive into results.
I have the following code:
>>>from datetime import datetime
>>>a = '2013-08-23T23:37:38+0000'
>>>dt = datetime.strptime(a,'%Y-%m-%dT%H:%M:%S+0000')
>>>print dt.date()
2013-08-23
>>>print dt.time()
23:37:38
What is the simplest way to output this result (assuming of course that a is unknown) given that we live in Central Europe. So it should be "daylight saving-proof" as well.
In winter:
2013-08-24
00:37:38
In summer:
2013-08-24
01:37:38
If it only needs default libraries it would be great.
Some more info
I dived into the libraries after my question. My above 3rd line should be better be:
dt = datetime.strptime(a,'%Y-%m-%dT%H:%M:%S%z'). However a bug came out in 2.7.5 python (OS X if it matters) and had some trouble finding the %z. If you have trouble change version, if not ignore this. Of course the strptime() is just simpler level of dateutil.parser mentioned in the two answers so it can better be used instead of my code above.
you can use the useful dateutil package and the pytz one for exemple convert to paris timezone
from dateutil import parser
import pytz
FR = pytz.timezone('Europe/Paris') # there is the summer offset changing in this zone
date = parser.parse("2013-08-23T23:37:38+0000")
datefr = date.astimezone(FR)
Here's an example using pytz and dateutil:
from dateutil import parser
import pytz
date = parser.parse('2013-08-23T23:37:38+0000')
CET = pytz.timezone('CET')
date = date.astimezone(CET)
print date.date() # prints 2013-08-24
print date.time() # prints 01:37:38

Convert python datetime to epoch with strftime

I have a time in UTC from which I want the number of seconds since epoch.
I am using strftime to convert it to the number of seconds. Taking 1st April 2012 as an example.
>>>datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'
1st of April 2012 UTC from epoch is 1333238400 but this above returns 1333234800 which is different by 1 hour.
So it looks like that strftime is taking my system time into account and applies a timezone shift somewhere. I thought datetime was purely naive?
How can I get around that? If possible avoiding to import other libraries unless standard. (I have portability concerns).
If you want to convert a python datetime to seconds since epoch you could do it explicitly:
>>> (datetime.datetime(2012,4,1,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0
In Python 3.3+ you can use timestamp() instead:
>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0
Why you should not use datetime.strftime('%s')
Python doesn't actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it's not in the list), the only reason it's working is because Python is passing the information to your system's strftime, which uses your local timezone.
>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'
I had serious issues with Timezones and such. The way Python handles all that happen to be pretty confusing (to me). Things seem to be working fine using the calendar module (see links 1, 2, 3 and 4).
>>> import datetime
>>> import calendar
>>> aprilFirst=datetime.datetime(2012, 04, 01, 0, 0)
>>> calendar.timegm(aprilFirst.timetuple())
1333238400
import time
from datetime import datetime
now = datetime.now()
time.mktime(now.timetuple())
import time
from datetime import datetime
now = datetime.now()
# same as above except keeps microseconds
time.mktime(now.timetuple()) + now.microsecond * 1e-6
(Sorry, it wouldn't let me comment on existing answer)
if you just need a timestamp in unix /epoch time, this one line works:
created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L
and depends only on datetime
works in python2 and python3
For an explicit timezone-independent solution, use the pytz library.
import datetime
import pytz
pytz.utc.localize(datetime.datetime(2012,4,1,0,0), is_dst=False).timestamp()
Output (float): 1333238400.0
This works in Python 2 and 3:
>>> import time
>>> import calendar
>>> calendar.timegm(time.gmtime())
1504917998
Just following the official docs...
https://docs.python.org/2/library/time.html#module-time
In Python 3.7
Return a datetime corresponding to a date_string in one of the formats
emitted by date.isoformat() and datetime.isoformat(). Specifically,
this function supports strings in the format(s)
YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]], where *
can match any single character.
https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat

Google app engine datastore datetime to date in Python?

I've always hated the headache of managine dates, times, datetimes, and the various formats and conversions that are needed with them. I'm taking an online course on using the google app engine and it says to use the datetime property, which is returning a date in the format:
2012-06-25 01:17:40.273000
I tried
datetime.strptime('2012-06-25 01:17:40.273000','%y-%m-%d %H:%M:%S')
but it didn't work..
I just want to extract the 2012-06-25 part without using a hacky regex or string slicing solution.
How do I parse this and convert it to the proper format?
Finally found it (shortly after asking the question, but I've been trying for the past hour)
datetime.strptime('2012-06-25 01:17:40.273000','%Y-%m-%d %H:%M:%S.%f')
What I wanted:
datetime.strptime('2012-06-25 01:17:40.273000','%Y-%m-%d %H:%M:%S.%f').strftime('%m-%d-%Y')
If you are using a datetime property then the object you get back is a datetime instance not a string.
On the console
>>> from datetime import datetime
>>> x = datetime.now()
>>> print x
2012-06-25 12:03:15.835467
>>> x.date()
datetime.date(2012, 6, 25)
>>>
>>> print x.date()
2012-06-25
>>>
See the print statement. It does an implicit conversion to string. If your outputting the datetime property value in a template, this is probably what is happening.
So in your code you should just use .date() method on the datetime object.

Categories

Resources