Convert datetime to local python - 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

Related

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']

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 ...

Local Time To UTC time pytz

I converted python datetime with help of pytz.
Convertion is like this
2013-08-23T09:53:03 to 2013-08-23T15:23:03+05:30 (time is changed
according timezone)
now the problem is "At at another loaction i get time as string 2013-08-23T15:23:03+05:30 how can i convert this string to 2013-08-23T09:53:03
thanks in advance
You can use the very useful dateutil package
from dateutil import parser
import pytz
UTC = pytz.timezone('UTC')
date = parser.parse("2013-08-23T15:23:03+05:30")
dateutc = date.astimezone(UTC)
print dateutc.isoformat()
# or user strptime to have in the format you want (without time zone)
print dateutc.strftime("%Y-%m-%dT%H:%M:%S")

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

converting a date to string for manipulation in python

I am new to python and i have written a script that converts a string date coming in to a datetime format going out. My problem is that cannot convert the datetime object back to a string for manipulation. i have a date eg 2011-08-10 14:50:10 all i need to to is add a T between the date and time and a Z at the end. unfortunately im using python 2.3 as my application will only accept that.
my code is as follows:
fromValue= ''
fromValue = document.Get(self._generic3)
fromValue = fromValue[:fromValue.rindex(" ")]
fromValue = datetime.datetime.fromtimestamp(time.mktime(time.strptime(fromValue,"%a, %d %b %Y %H:%M:%S")))
toValue = fromValue.strftime("%Y-%m-%dT %H:%M:%SZ")
This should work fine. datetime.strftime was available on Python 2.3.
You'd certainly be better off upgrading to at least Python 2.5 if at all possible. Python 2.3 hasn't even received security patches in years.
Edit: Also, you don't need to initialize or declare variables in Python; the fromValue= '' has no effect on your program.
Edit 2: In a comment, you seem to have said you have it in a string already in nearly the right format:
"2011-08-08 14:15:21"
so just do
'T'.join("2011-08-08 14:15:21".split()) + 'Z'
If you want to add the letters while it's a string.
It looks like you are trying to format the datetime in ISO-8601 format.
For this purpose, use the isoformat method.
import datetime as dt
try:
import email.utils as eu
except ImportError:
import email.Utils as eu # for Python 2.3
date_string="Fri, 08 Aug 2011 14:15:10 -0400"
ttuple=eu.parsedate(date_string)
date=dt.datetime(*ttuple[:6])
print(date.isoformat()+'Z')
yields
2011-08-08T14:15:10Z
Here is link to isoformat and parsedate in the Python2.3 docs.
fromValue.strftime('%Y-%m-%d T %H:%M:%S Z')
http://docs.python.org/release/2.3/lib/module-time.html
http://docs.python.org/release/2.3/lib/node208.html

Categories

Resources