unbale to convert localtime to utc using python - python-2.7

I am trying to convert local date time to UTC format but I am unable to convert Please let me know how to get required output using following input
Input : 2008-09-17 10:45:00 PM
Output : 2008-09-17 17:15:00 PM
required output: 1715UTC
from datetime import *
from dateutil import *
from dateutil.tz import tz
utc_zone = tz.gettz('UTC')
local_zone = tz.gettz('Asia/kolkata')
utc_zone = tz.tzutc()
local_zone = tz.tzlocal()
# Convert time string to datetime
local_time = datetime.strptime("2008-09-17 10:45:00 PM", '%Y-%m-%d %I:%M:%S %p')
local_time = local_time.replace(tzinfo=local_zone)
utc_time = local_time.astimezone(utc_zone)
utc_string = utc_time.strftime('%Y-%m-%d %H:%M:%S %p')
print utc_string

See this:
How do I convert local time to UTC in Python?
It shows how to format the time as per your requirements.

Related

How to convert into UTC time with params provided as below?

If date is provided as as 01st Jan, 2nd Jan, it should provide me an output in UTC along with current year and time as well.
Output : 2017-01-02T06:40:00Z
You cannot only use datetime module since the ordinals are not handled.
But you can use a regular expression to reformat your input, and then strptime to convert it to a datetime that you can convert back to string using strftime:
import re
import datetime
str_date = "2nd Jan"
now = datetime.datetime.utcnow()
PATTERN = re.compile(r"^0*(?P<day>[1-9]\d*)[^ ]* (?P<month>\w+)$")
reformatted = PATTERN.sub(r"\g<day> \g<month> %s", str_date) % now.strftime("%Y %H:%M:%S")
date = datetime.datetime.strptime(reformatted, "%d %b %Y %H:%M:%S")
print date.strftime("%Y-%m-%dT%H:%M:%SZ")
will output : 2017-01-02T09:03:54Z

How to convert time.strptime into an integer for datatime.date() Python 2

How would I convert the result from strptime into an integer value or a value that can be used by date.date()?
convertTOdate = time.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S')
duedate = datetime.datetime(convertTOdate)
A Solution on stackoverflow was to do:
Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.
from time import mktime
from datetime import datetime
dt = datetime.fromtimestamp(mktime(struct))
I do not want to get the local time as it would not work with my function
I am using Python 2
Thank you
You can use the following approach.
from datetime import datetime
def time_in_seconds(dt):
epoch = datetime.utcfromtimestamp(0)
delta = dt - epoch
return delta.total_seconds()
convertTOdate = datetime.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S')
duedate = time_in_seconds(convertTOdate)
returns 1184752999.0 which is equivalent to 2007-07-18 10:03:19
duedate = datetime.utcfromtimestamp(duedate)
print duedate
Just remember before using the following two:
fromtimestamp give you the date and time in local time and utcfromtimestamp gives you the date and time in UTC.

Django: How-to convert naive datetime when time zone support is active?

I'm struggeling with Django and datetime.
I have a datetime-string as this "Sun, 28 Aug 2016 11:42:00 +0200" - so from my point of view including timezone information "+0200"
Then I convert it using this:
date_published = time.strptime(date_published, "%a, %d %b %Y %H:%M:%S %z")
It gives me this:
time.struct_time(tm_year=2016, tm_mon=8, tm_mday=28, tm_hour=11, tm_min=42, tm_sec=0, tm_wday=6, tm_yday=241, tm_isdst=-1)
Then I try to convert it like this:
date_published = datetime.fromtimestamp(time.mktime(date_published))
Which gives me:
2016-08-28 11:42:00
And then Django complains when saving it with the following warning:
RuntimeWarning: DateTimeField ModelName.field_name received a naive
datetime (2012-01-01 00:00:00) while time zone support is active.
How do I correctly convert the input string so that I can save it into a timezone aware datetime-model's fields?
Best Regeards
Kev
Python itself can't handle timezones. You need external library to do it. For example dateutil:
from dateutil.parser import parse
dt = parse("Sun, 28 Aug 2016 11:42:00 +0200")
This alone should work:
from datetime import datetime
date_published = datetime.strptime(date_published, "%a, %d %b %Y %H:%M:%S %z")
The return I get is datetime.datetime(2016, 8, 28, 11, 42, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))

how to get UTC offset value from timezone?

In my Django project, I have a form (forms.py) which implements pytz to get current timezone like this:
tz = timezone.get_current_timezone()
and I have passed this value to a form field as an initial value like this:
timezone = forms.CharField(label='Time Zone', initial=tznow)
which gives the field a default value of current Timezone, in my case, it happens to be Asia/Calcutta.
Now i want to find the UTC Offset value for the given Timezone, which in this case Asia/Calcutta is +5:30
I tried tzinfo() method as well, but i couldn't find the expected result. Can somebody guide me through this?
The UTC offset is given as a timedelta by the utcoffset method of any implementation of tzinfo such as pytz. For example:
import pytz
import datetime
tz = pytz.timezone('Asia/Calcutta')
dt = datetime.datetime.utcnow()
offset_seconds = tz.utcoffset(dt).total_seconds()
offset_hours = offset_seconds / 3600.0
print "{:+d}:{:02d}".format(int(offset_hours), int((offset_hours % 1) * 60))
# +5:30
A single timezone such as Asia/Calcutta may have different utc offsets at different dates. You can enumerate the utc offsets known so far using pytz's _tzinfos in this case:
>>> offsets = {off for off, dst, abbr in pytz.timezone('Asia/Calcutta')._tzinfos}
>>> for utc_offset in offsets:
... print(utc_offset)
...
5:30:00
6:30:00
5:53:00
To get the current utc offset for a given timezone:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
utc_offset = datetime.now(pytz.timezone('Asia/Calcutta')).utcoffset()
print(utc_offset)
# -> 5:30:00
In case you just want the normalized hour offset:
def curr_calcutta_offset():
tz_calcutta = pytz.timezone('Asia/Calcutta')
offset = tz_calcutta.utcoffset(datetime.utcnow())
offset_seconds = (offset.days * 86400) + offset.seconds
offset_hours = offset_seconds / 3600
return offset_hours
curr_calcutta_offset()
# 5.5

strange timestamp and timedelta formats - how to convert them?

I am using external api which returns dates (as strings) in a strange format:
2012-09-26T15:44:10.376000 #timestamp
0:00:01.714000 #delta (some time duration)
I want to convert them to this format:
19 Sep 2012 17:02
0:17:34
Is there easy way to do this?
I can convert them in my view or in template
edit -----------------------------------------------------------
I found solution for timestamp:
date_str = '2012-09-26T15:44:10.376000'
date = datetime.strptime(date_str.split('.')[0],'%Y-%m-%dT%H:%M:%S')
str = date.strftime('%m %b %Y %H:%M')
Install dateutil and then:
>>> import dateutil.parser
>>> dt = dateutil.parser.parse('2012-09-26T15:44:10.376000')
>>> dt.strftime('%d %b %Y %H:%M')
'26 Sep 2012 15:44'
For django, you can pass the dt object to your template and use the date filter:
{{ dt|date:"d b Y H:M" }}