How to convert string date to a epoch timestamp in python - 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")

Related

Python datetime.today() to handle timezone

Hi apologies on basic python datetime question but I am a little confused:
I want to just have a variable the prints today's date, with consideration to the time zone the program I am running it in. Let's say California.
import datetime
import pytz
utc_now = pytz.utc.localize(datetime.datetime.utcnow())
pst_now = utc_now.astimezone(pytz.timezone("America/Los_Angeles"))
x = pst_now.isoformat()
for x it returns :
2020-01-13T17:43:56.155556-08:00
how can I get it to return:
2020-01-13
I tried:
datetime.datetime.strptime(x, '%Y-%m-%d)
But it did not work
If you're just looking to return the time of the local machine, no need to deal with timezones directly in your code, you can use the now function of datetime.
import datetime
datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')
x is a string. pst_now is a datetime object which, when the method .isoformat() is called on it, produces a string.
Solution: call strftime on pst_now:
x = pst_now.strftime('%Y-%m-%d')
You can convert pst_now to a date() object:
pst_now.date().isoformat()
'2020-01-13'

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.

python convert human to timestamp

My date is in following format:
19/Jun/2014:00:03:09
How to I convert it to epoch timestamp in python?
Note: I searched on date format in python, but could not find any format that matches above.
Thanks.
Use strptime and then mktime.
import time
tt = time.strptime("19/Jun/2014:00:03:09","%d/%b/%Y:%H:%M:%S")
print time.mktime(tt)
import datetime
datetime.datetime.strptime(s, '%d/%b/%Y:%H:%M:%S')
reference
use dateutil it will parse just about anything
$ easy_install python-dateutil
>>> import dateutil.parser as parser
>>> some_date_string = "19/Jun/2014:00:03:09"
>>> parser.parse(some_date_string)
[edit] oops nevermind ... apparently it cant parse this ...

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

Python: serializing/deserializing datetime.time

I have a form with dropdowns full of times, represented with datetime.time objects.
What's the best way to serialize the object? eg:
<option value="${time.serialize()}">${time.isoformat()}</option>
And then deserialize it on the other end? eg:
time = datetime.time.deserialize(request.params['time'])
If you repr a datetime.time object, Python gives you isoformat. As reprs attempt to be serialized versions of their objects, that's a good indication it's the value you should use.
import datetime
timestring = datetime.datetime.now().time().isoformat()
timeobj = datetime.datetime.strptime(timestring, "%H:%M:%S.%f").time()
In Python 3.6 and newer you can use the datetime.time.isoformat function to serialize and in Python 3.7 and newer you can use the datetime.time.fromisoformat function to deserialize. So it would look like this
import datetime
time_string = datetime.datetime.now().time().isoformat()
time_obj = datetime.time.fromisoformat(time_string)
and to do this with a datetime instead of a time, it would look like
import datetime
datetime_string = datetime.datetime.now().isoformat()
datetime_obj = datetime.datetime.fromisoformat(datetime_string)

Categories

Resources