Convert python datetime to epoch with strftime - python

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

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'

converting between timezones (format same instance in time) in python 3

I have a list of timestamps which look like so:
time_list=['2016-10-01T00:00:00+01:00','2016-10-01T23:00:00+00:00','2016-10-01T22:00:00+02:00',..]
I would like to apply a magic function to this list which gets them all in +00:00 timezone - this should result in (all timestamps should correctly adjusted to the +00:00 format):
ret_list=['2016-10-01T23:00:00+00:00','2016-10-01T23:00:00+00:00','2016-10-01T23:00:00+00:00',..]
You have to convert your isoformat strings to datetime objects first, change timezones to UTC and then stringify back.
If you are on python 3.7, according to this, you can use fromisoformat method of datetime, but if you don't, like me, I think the best option involves the use of dateutil module (you have to install it) and pytz:
import datetime as dt
from dateutil import parser
import pytz
time_list = ['2016-10-01T00:00:00+01:00','2016-10-01T23:00:00+00:00','2016-10-01T22:00:00+02:00']
utc_time_list = [parser.parse(x).astimezone(pytz.utc).isoformat() for x in time_list]
print(utc_time_list)
['2016-09-30T23:00:00+00:00', '2016-10-01T23:00:00+00:00', '2016-10-01T20:00:00+00:00']

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")

Not working Python miliseconds time

I have read all posts in Stackoverflow, documentation for "time" in python docs, but not found how to make float time.
import time
time.strftime('%H:%M:%S.%f', time.gmtime(60.5))
returns 00:01:00.%f
I want take 00:01:00.500
I wasn't able to find similar question.
Final solution is:
datetime.datetime.utcfromtimestamp(60.5).strftime('%H:%M:%S')+'.'+str(int(int(datetime.datetime.utcfromtimestamp(60.5).strftime('%f'))/1000))
The time module does not support the %f millisecond formatter because the time.struct_time tuple doesn't support milliseconds.
The datetime module does support milliseconds. Use that module instead:
import datetime
datetime.datetime.utcfromtimestamp(60.5).strftime('%H:%M:%S.%f')
Demo:
>>> datetime.datetime.utcfromtimestamp(60.5).strftime('%H:%M:%S.%f')
'00:01:00.500000'
Actually %f are microseconds:
from datetime import datetime
'{:%H:%M:%S.%f}'.format(datetime.utcfromtimestamp(60.5))
returns
00:01:00.500000

Parsing timestamp with Python2.4

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

Categories

Resources