Setting timezone in Python - python

Is it possible with Python to set the timezone just like this in PHP:
date_default_timezone_set("Europe/London");
$Year = date('y');
$Month = date('m');
$Day = date('d');
$Hour = date('H');
$Minute = date('i');
I can't really install any other modules etc as I'm using shared web hosting.
Any ideas?

>>> import os, time
>>> time.strftime('%X %x %Z')
'12:45:20 08/19/09 CDT'
>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()
>>> time.strftime('%X %x %Z')
'18:45:39 08/19/09 BST'
To get the specific values you've listed:
>>> year = time.strftime('%Y')
>>> month = time.strftime('%m')
>>> day = time.strftime('%d')
>>> hour = time.strftime('%H')
>>> minute = time.strftime('%M')
See here for a complete list of directives. Keep in mind that the strftime() function will always return a string, not an integer or other type.

Be aware that running
import os
os.system("tzutil /s \"Central Standard Time\"");
will alter Windows system time, NOT just the local python environment time (so is definitley NOT the same as:
>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()
which will only set in the current environment time (in Unix only)

For windows you can use:
Running Windows command prompt commands in python.
import os
os.system('tzutil /s "Central Standard Time"')
In windows command prompt try:
This gives current timezone:
tzutil /g
This gives a list of timezones:
tzutil /l
This will set the timezone:
tzutil /s "Central America Standard Time"
For further reference:
http://woshub.com/how-to-set-timezone-from-command-prompt-in-windows/

You can use pytz as well..
import datetime
import pytz
def utcnow():
return datetime.datetime.now(tz=pytz.utc)
utcnow()
datetime.datetime(2020, 8, 15, 14, 45, 19, 182703, tzinfo=<UTC>)
utcnow().isoformat()
'
2020-08-15T14:45:21.982600+00:00'

It's not an answer, but...
To get datetime components individually, better use datetime.timetuple:
time = datetime.now()
time.timetuple()
#-> time.struct_time(
# tm_year=2014, tm_mon=9, tm_mday=7,
# tm_hour=2, tm_min=38, tm_sec=5,
# tm_wday=6, tm_yday=250, tm_isdst=-1
#)
It's now easy to get the parts:
ts = time.timetuple()
ts.tm_year
ts.tm_mon
ts.tm_mday
ts.tm_hour
ts.tm_min
ts.tm_sec

Related

Strip Leading Zeroes from Date [duplicate]

When using Python strftime, is there a way to remove the first 0 of the date if it's before the 10th, ie. so 01 is 1? Can't find a %thingy for that?
Thanks!
Actually I had the same problem and I realized that, if you add a hyphen between the % and the letter, you can remove the leading zero.
For example %Y/%-m/%-d.
This only works on Unix (Linux, OS X), not Windows (including Cygwin). On Windows, you would use #, e.g. %Y/%#m/%#d.
We can do this sort of thing with the advent of the format method since python2.6:
>>> import datetime
>>> '{dt.year}/{dt.month}/{dt.day}'.format(dt = datetime.datetime.now())
'2013/4/19'
Though perhaps beyond the scope of the original question, for more interesting formats, you can do stuff like:
>>> '{dt:%A} {dt:%B} {dt.day}, {dt.year}'.format(dt=datetime.datetime.now())
'Wednesday December 3, 2014'
And as of python3.6, this can be expressed as an inline formatted string:
Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dt = datetime.datetime.now()
>>> f'{dt:%A} {dt:%B} {dt.day}, {dt.year}'
'Monday August 29, 2016'
Some platforms may support width and precision specification between % and the letter (such as 'd' for day of month), according to http://docs.python.org/library/time.html -- but it's definitely a non-portable solution (e.g. doesn't work on my Mac;-). Maybe you can use a string replace (or RE, for really nasty format) after the strftime to remedy that? e.g.:
>>> y
(2009, 5, 7, 17, 17, 17, 3, 127, 1)
>>> time.strftime('%Y %m %d', y)
'2009 05 07'
>>> time.strftime('%Y %m %d', y).replace(' 0', ' ')
'2009 5 7'
Here is the documentation of the modifiers supported by strftime() in the GNU C library. (Like people said before, it might not be portable.) Of interest to you might be:
%e instead of %d will replace leading zero in day of month with a space
It works on my Python (on Linux). I don't know if it will work on yours.
>>> import datetime
>>> d = datetime.datetime.now()
>>> d.strftime('X%d/X%m/%Y').replace('X0','X').replace('X','')
'5/5/2011'
On Windows, add a '#', as in '%#m/%#d/%Y %#I:%M:%S %p'
For reference: https://msdn.microsoft.com/en-us/library/fe06s4ak.aspx
quite late to the party but %-d works on my end.
datetime.now().strftime('%B %-d, %Y') produces something like "November 5, 2014"
cheers :)
Take a look at - bellow:
>>> from datetime import datetime
>>> datetime.now().strftime('%d-%b-%Y')
>>> '08-Oct-2011'
>>> datetime.now().strftime('%-d-%b-%Y')
>>> '8-Oct-2011'
>>> today = datetime.date.today()
>>> today.strftime('%d-%b-%Y')
>>> print(today)
I find the Django template date formatting filter to be quick and easy. It strips out leading zeros. If you don't mind importing the Django module, check it out.
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
from django.template.defaultfilters import date as django_date_filter
print django_date_filter(mydate, 'P, D M j, Y')
simply use replace like this:
(datetime.date.now()).strftime("%Y/%m/%d").replace("/0", "/")
it will output:
'2017/7/21'
For %d you can convert to integer using int() then it'll automatically remove leading 0 and becomes integer. You can then convert back to string using str().
using, for example, "%-d" is not portable even between different versions of the same OS.
A better solution would be to extract the date components individually, and choose between date specific formatting operators and date attribute access for each component.
e = datetime.date(2014, 1, 6)
"{date:%A} {date.day} {date:%B}{date.year}".format(date=e)
if we want to fetch only date without leading zero we can
d = date.today()
day = int(d.strftime("%d"))
Because Python really just calls the C language strftime(3) function on your platform, it might be that there are format characters you could use to control the leading zero; try man strftime and take a look. But, of course, the result will not be portable, as the Python manual will remind you. :-)
I would try using a new-style datetime object instead, which has attributes like t.year and t.month and t.day, and put those through the normal, high-powered formatting of the % operator, which does support control of leading zeros. See http://docs.python.org/library/datetime.html for details. Better yet, use the "".format() operator if your Python has it and be even more modern; it has lots of format options for numbers as well. See: http://docs.python.org/library/string.html#string-formatting.
Based on Alex's method, this will work for both the start-of-string and after-spaces cases:
re.sub('^0|(?<= )0', '', "01 January 2000 08:00am")
I like this better than .format or %-d because this is cross-platform and allows me to keep using strftime (to get things like "November" and "Monday").
Old question, but %l (lower-case L) worked for me in strftime: this may not work for everyone, though, as it's not listed in the Python documentation I found
import datetime
now = datetime.datetime.now()
print now.strftime("%b %_d")
Python 3.6+:
from datetime import date
today = date.today()
text = "Today it is " + today.strftime(f"%A %B {today.day}, %Y")
I am late, but a simple list slicing will do the work
today_date = date.today().strftime('%d %b %Y')
if today_date[0] == '0':
today_date = today_date[1:]
The standard library is good enough for most cases but for a really detailed manipulation with dates you should always look for some specialized third-party library.
Using Arrow:
>>> import arrow
>>> arrow.utcnow().format('dddd, D. M. YYYY')
'Friday, 6. 5. 2022'
Look at the full list of supported tokens.
A little bit tricky but works for me
ex. from 2021-02-01T00:00:00.000Z to 2021-02-1
from datetime import datetime
dateObj = datetime.strptime('2021-02-01T00:00:00.000Z','%Y-%m-%dT%H:%M:%S.%fZ')
dateObj.strftime('%Y-%m-{}').format(dateObj.day)

ValueError: time data '2021-04-06T23:51:50.514Z' does not match format '%Y-%m-%dT%H:%M:%SZ' when converting ISO 8601 [duplicate]

This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 8 years ago.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
I'm getting a datetime string in a format like "2009-05-28T16:15:00" (this is ISO 8601, I believe). One hackish option seems to be to parse the string using time.strptime and passing the first six elements of the tuple into the datetime constructor, like:
datetime.datetime(*time.strptime("2007-03-04T21:08:12", "%Y-%m-%dT%H:%M:%S")[:6])
I haven't been able to find a "cleaner" way of doing this. Is there one?
I prefer using the dateutil library for timezone handling and generally solid date parsing. If you were to get an ISO 8601 string like: 2010-05-08T23:41:54.000Z you'd have a fun time parsing that with strptime, especially if you didn't know up front whether or not the timezone was included. pyiso8601 has a couple of issues (check their tracker) that I ran into during my usage and it hasn't been updated in a few years. dateutil, by contrast, has been active and worked for me:
from dateutil import parser
yourdate = parser.parse(datestring)
Since Python 3.7 and no external libraries, you can use the fromisoformat function from the datetime module:
datetime.datetime.fromisoformat('2019-01-04T16:41:24+02:00')
Python 2 doesn't support the %z format specifier, so it's best to explicitly use Zulu time everywhere if possible:
datetime.datetime.strptime("2007-03-04T21:08:12Z", "%Y-%m-%dT%H:%M:%SZ")
Because ISO 8601 allows many variations of optional colons and dashes being present, basically CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]. If you want to use strptime, you need to strip out those variations first.
The goal is to generate a UTC datetime object.
If you just want a basic case that work for UTC with the Z suffix like 2016-06-29T19:36:29.3453Z:
datetime.datetime.strptime(timestamp.translate(None, ':-'), "%Y%m%dT%H%M%S.%fZ")
If you want to handle timezone offsets like 2016-06-29T19:36:29.3453-0400 or 2008-09-03T20:56:35.450686+05:00 use the following. These will convert all variations into something without variable delimiters like 20080903T205635.450686+0500 making it more consistent/easier to parse.
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
datetime.datetime.strptime(conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" )
If your system does not support the %z strptime directive (you see something like ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z') then you need to manually offset the time from Z (UTC). Note %z may not work on your system in Python versions < 3 as it depended on the C library support which varies across system/Python build type (i.e., Jython, Cython, etc.).
import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split(r"([+|-])",conformed_timestamp)
main_timestamp = split_timestamp[0]
if len(split_timestamp) == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime(main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" )
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
Arrow looks promising for this:
>>> import arrow
>>> arrow.get('2014-11-13T14:53:18.694072+00:00').datetime
datetime.datetime(2014, 11, 13, 14, 53, 18, 694072, tzinfo=tzoffset(None, 0))
Arrow is a Python library that provides a sensible, intelligent way of creating, manipulating, formatting and converting dates and times. Arrow is simple, lightweight and heavily inspired by moment.js and requests.
You should keep an eye on the timezone information, as you might get into trouble when comparing non-tz-aware datetimes with tz-aware ones.
It's probably the best to always make them tz-aware (even if only as UTC), unless you really know why it wouldn't be of any use to do so.
#-----------------------------------------------
import datetime
import pytz
import dateutil.parser
#-----------------------------------------------
utc = pytz.utc
BERLIN = pytz.timezone('Europe/Berlin')
#-----------------------------------------------
def to_iso8601(when=None, tz=BERLIN):
if not when:
when = datetime.datetime.now(tz)
if not when.tzinfo:
when = tz.localize(when)
_when = when.strftime("%Y-%m-%dT%H:%M:%S.%f%z")
return _when[:-8] + _when[-5:] # Remove microseconds
#-----------------------------------------------
def from_iso8601(when=None, tz=BERLIN):
_when = dateutil.parser.parse(when)
if not _when.tzinfo:
_when = tz.localize(_when)
return _when
#-----------------------------------------------
I haven't tried it yet, but pyiso8601 promises to support this.
import datetime, time
def convert_enddate_to_seconds(self, ts):
"""Takes ISO 8601 format(string) and converts into epoch time."""
dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+\
datetime.timedelta(hours=int(ts[-5:-3]),
minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
return seconds
This also includes the milliseconds and time zone.
If the time is '2012-09-30T15:31:50.262-08:00', this will convert into epoch time.
>>> import datetime, time
>>> ts = '2012-09-30T15:31:50.262-08:00'
>>> dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+ datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
>>> seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
>>> seconds
1348990310.26
Both ways:
Epoch to ISO time:
isoTime = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(epochTime))
ISO time to Epoch:
epochTime = time.mktime(time.strptime(isoTime, '%Y-%m-%dT%H:%M:%SZ'))
Isodate seems to have the most complete support.
aniso8601 should handle this. It also understands timezones, Python 2 and Python 3, and it has a reasonable coverage of the rest of ISO 8601, should you ever need it.
import aniso8601
aniso8601.parse_datetime('2007-03-04T21:08:12')
Here is a super simple way to do these kind of conversions.
No parsing, or extra libraries required.
It is clean, simple, and fast.
import datetime
import time
################################################
#
# Takes the time (in seconds),
# and returns a string of the time in ISO8601 format.
# Note: Timezone is UTC
#
################################################
def TimeToISO8601(seconds):
strKv = datetime.datetime.fromtimestamp(seconds).strftime('%Y-%m-%d')
strKv = strKv + "T"
strKv = strKv + datetime.datetime.fromtimestamp(seconds).strftime('%H:%M:%S')
strKv = strKv +"Z"
return strKv
################################################
#
# Takes a string of the time in ISO8601 format,
# and returns the time (in seconds).
# Note: Timezone is UTC
#
################################################
def ISO8601ToTime(strISOTime):
K1 = 0
K2 = 9999999999
K3 = 0
counter = 0
while counter < 95:
K3 = (K1 + K2) / 2
strK4 = TimeToISO8601(K3)
if strK4 < strISOTime:
K1 = K3
if strK4 > strISOTime:
K2 = K3
counter = counter + 1
return K3
################################################
#
# Takes a string of the time in ISO8601 (UTC) format,
# and returns a python DateTime object.
# Note: returned value is your local time zone.
#
################################################
def ISO8601ToDateTime(strISOTime):
return time.gmtime(ISO8601ToTime(strISOTime))
#To test:
Test = "2014-09-27T12:05:06.9876"
print ("The test value is: " + Test)
Ans = ISO8601ToTime(Test)
print ("The answer in seconds is: " + str(Ans))
print ("And a Python datetime object is: " + str(ISO8601ToDateTime(Test)))

python: which file is newer & by how much time

I am trying to create a filedate comparison routine. I suspect that the following is a rather clunky approach.
I had some difficulty finding info about timedelta's attributes or methods, or whatever they are called; hence, I measured the datetime difference below only in terms of days, minutes and seconds, and there is no list item representing years.
Any suggestions for an alternative, would be much appreciated.
import os
import datetime
from datetime import datetime
import sys
def datetime_filedif(filepath1e, filepath2e):
filelpath1 = str(filepath1e)
filepath1 = str(filepath1e)
filepath2 = str(filepath2e)
filepath1_lmdate = datetime.fromtimestamp(os.path.getmtime(filepath1))
filepath2_lmdate = datetime.fromtimestamp(os.path.getmtime(filepath2))
td_files = filepath2_lmdate - filepath1_lmdate #Time delta of the 2 filedates
td_list = [('td_files.days', td_files.days), ('td_hrs', int(str(td_files.seconds))/3600), ('td_minutes', (int(str(td_files.seconds))%3600)/60), ('td_seconds', (int(str(td_files.seconds))%3600)%60)]
print "Line 25: ", str(td_list)
return td_list
There is a solution for that already:
import os
modified_time = os.stat(path).st_mtime # time of most recent content modification
diff_time = os.stat(path_1).st_mtime - os.stat(path_2).st_mtime
Now you have the time in seconds since Epoch. why are you creating a new representation, you can create a deltatime or whatever from this, why invent a new format?

Find the closest hour

I have a list with these items:
hours = ['19:30', '20:10', '20:30', '21:00', '22:00']
Assuming that now it's 20:18, how can I get the '20:10' item from list? I want to use this to find the current running show in a TV Guide.
>>> import datetime
>>> hours = ['19:30', '20:10', '20:30', '21:00', '22:00']
>>> now = datetime.datetime.strptime("20:18", "%H:%M")
>>> min(hours, key=lambda t: abs(now - datetime.datetime.strptime(t, "%H:%M")))
'20:10'
easy but dirty way
max(t for t in sorted(hours) if t<=now)
I'm not a Python programmer, but I'd use the following algorithm:
Convert everything to "minutes after midnight", e.g. hours = [1170 (= 19*60+30), 1210, ...], currenttime = 1218 (= 20*60+18).
Then just loop thorugh hours and find the last entry which is smaller than currenttime.
You can use functions in the time module; time.strptime() allows you to parse a string into a time-tuple, then time.mktime() converts this to seconds. You can then simply compare all items in seconds, and find the smallest difference.
#katrielalex & Tim
import itertools
[x for x in itertools.takewhile( lambda t: now > datetime.datetime.strptime(t, "%H:%M"), hours )][-1]
import bisect
# you can use the time module like katrielalex answer which a standard library
# in python, but sadly for me i become an addict to dateutil :)
from dateutil import parser
hour_to_get = parser.parse('20:18')
hours = ['19:30', '20:10', '20:30', '21:00', '22:00']
hours = map(parser.parse, hours) # Convert to datetime.
hours.sort() # In case the list of hours isn't sorted.
index = bisect.bisect(hours, hour_to_get)
if index in (0, len(hours) - 1):
print "there is no show running at the moment"
else:
print "running show started at %s " % hours[index-1]
Hope this can help you :)

How do I translate an ISO 8601 datetime string into a Python datetime object? [duplicate]

This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 8 years ago.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
I'm getting a datetime string in a format like "2009-05-28T16:15:00" (this is ISO 8601, I believe). One hackish option seems to be to parse the string using time.strptime and passing the first six elements of the tuple into the datetime constructor, like:
datetime.datetime(*time.strptime("2007-03-04T21:08:12", "%Y-%m-%dT%H:%M:%S")[:6])
I haven't been able to find a "cleaner" way of doing this. Is there one?
I prefer using the dateutil library for timezone handling and generally solid date parsing. If you were to get an ISO 8601 string like: 2010-05-08T23:41:54.000Z you'd have a fun time parsing that with strptime, especially if you didn't know up front whether or not the timezone was included. pyiso8601 has a couple of issues (check their tracker) that I ran into during my usage and it hasn't been updated in a few years. dateutil, by contrast, has been active and worked for me:
from dateutil import parser
yourdate = parser.parse(datestring)
Since Python 3.7 and no external libraries, you can use the fromisoformat function from the datetime module:
datetime.datetime.fromisoformat('2019-01-04T16:41:24+02:00')
Python 2 doesn't support the %z format specifier, so it's best to explicitly use Zulu time everywhere if possible:
datetime.datetime.strptime("2007-03-04T21:08:12Z", "%Y-%m-%dT%H:%M:%SZ")
Because ISO 8601 allows many variations of optional colons and dashes being present, basically CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]. If you want to use strptime, you need to strip out those variations first.
The goal is to generate a UTC datetime object.
If you just want a basic case that work for UTC with the Z suffix like 2016-06-29T19:36:29.3453Z:
datetime.datetime.strptime(timestamp.translate(None, ':-'), "%Y%m%dT%H%M%S.%fZ")
If you want to handle timezone offsets like 2016-06-29T19:36:29.3453-0400 or 2008-09-03T20:56:35.450686+05:00 use the following. These will convert all variations into something without variable delimiters like 20080903T205635.450686+0500 making it more consistent/easier to parse.
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
datetime.datetime.strptime(conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" )
If your system does not support the %z strptime directive (you see something like ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z') then you need to manually offset the time from Z (UTC). Note %z may not work on your system in Python versions < 3 as it depended on the C library support which varies across system/Python build type (i.e., Jython, Cython, etc.).
import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split(r"([+|-])",conformed_timestamp)
main_timestamp = split_timestamp[0]
if len(split_timestamp) == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime(main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" )
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
Arrow looks promising for this:
>>> import arrow
>>> arrow.get('2014-11-13T14:53:18.694072+00:00').datetime
datetime.datetime(2014, 11, 13, 14, 53, 18, 694072, tzinfo=tzoffset(None, 0))
Arrow is a Python library that provides a sensible, intelligent way of creating, manipulating, formatting and converting dates and times. Arrow is simple, lightweight and heavily inspired by moment.js and requests.
You should keep an eye on the timezone information, as you might get into trouble when comparing non-tz-aware datetimes with tz-aware ones.
It's probably the best to always make them tz-aware (even if only as UTC), unless you really know why it wouldn't be of any use to do so.
#-----------------------------------------------
import datetime
import pytz
import dateutil.parser
#-----------------------------------------------
utc = pytz.utc
BERLIN = pytz.timezone('Europe/Berlin')
#-----------------------------------------------
def to_iso8601(when=None, tz=BERLIN):
if not when:
when = datetime.datetime.now(tz)
if not when.tzinfo:
when = tz.localize(when)
_when = when.strftime("%Y-%m-%dT%H:%M:%S.%f%z")
return _when[:-8] + _when[-5:] # Remove microseconds
#-----------------------------------------------
def from_iso8601(when=None, tz=BERLIN):
_when = dateutil.parser.parse(when)
if not _when.tzinfo:
_when = tz.localize(_when)
return _when
#-----------------------------------------------
I haven't tried it yet, but pyiso8601 promises to support this.
import datetime, time
def convert_enddate_to_seconds(self, ts):
"""Takes ISO 8601 format(string) and converts into epoch time."""
dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+\
datetime.timedelta(hours=int(ts[-5:-3]),
minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
return seconds
This also includes the milliseconds and time zone.
If the time is '2012-09-30T15:31:50.262-08:00', this will convert into epoch time.
>>> import datetime, time
>>> ts = '2012-09-30T15:31:50.262-08:00'
>>> dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+ datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
>>> seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
>>> seconds
1348990310.26
Both ways:
Epoch to ISO time:
isoTime = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(epochTime))
ISO time to Epoch:
epochTime = time.mktime(time.strptime(isoTime, '%Y-%m-%dT%H:%M:%SZ'))
Isodate seems to have the most complete support.
aniso8601 should handle this. It also understands timezones, Python 2 and Python 3, and it has a reasonable coverage of the rest of ISO 8601, should you ever need it.
import aniso8601
aniso8601.parse_datetime('2007-03-04T21:08:12')
Here is a super simple way to do these kind of conversions.
No parsing, or extra libraries required.
It is clean, simple, and fast.
import datetime
import time
################################################
#
# Takes the time (in seconds),
# and returns a string of the time in ISO8601 format.
# Note: Timezone is UTC
#
################################################
def TimeToISO8601(seconds):
strKv = datetime.datetime.fromtimestamp(seconds).strftime('%Y-%m-%d')
strKv = strKv + "T"
strKv = strKv + datetime.datetime.fromtimestamp(seconds).strftime('%H:%M:%S')
strKv = strKv +"Z"
return strKv
################################################
#
# Takes a string of the time in ISO8601 format,
# and returns the time (in seconds).
# Note: Timezone is UTC
#
################################################
def ISO8601ToTime(strISOTime):
K1 = 0
K2 = 9999999999
K3 = 0
counter = 0
while counter < 95:
K3 = (K1 + K2) / 2
strK4 = TimeToISO8601(K3)
if strK4 < strISOTime:
K1 = K3
if strK4 > strISOTime:
K2 = K3
counter = counter + 1
return K3
################################################
#
# Takes a string of the time in ISO8601 (UTC) format,
# and returns a python DateTime object.
# Note: returned value is your local time zone.
#
################################################
def ISO8601ToDateTime(strISOTime):
return time.gmtime(ISO8601ToTime(strISOTime))
#To test:
Test = "2014-09-27T12:05:06.9876"
print ("The test value is: " + Test)
Ans = ISO8601ToTime(Test)
print ("The answer in seconds is: " + str(Ans))
print ("And a Python datetime object is: " + str(ISO8601ToDateTime(Test)))

Categories

Resources