strange timestamp and timedelta formats - how to convert them? - django

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

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

unbale to convert localtime to utc using python

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.

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

Would DateTimeField() work if I have time in this format 1/7/11 9:15 ? If not what would?

I am importing data from a JSON file and it has the date in the following format 1/7/11 9:15
What would be the best variable type/format to define in order to accept this date as it is? If not what would be the most efficient way to accomplish this task?
Thanks.
"What would be the best variable type/format to define in order to accept this date as it is?"
The DateTimeField.
"If not what would be the most efficient way to accomplish this task?"
You should use the datetime.strptime method from Python's builtin datetime library:
>>> from datetime import datetime
>>> import json
>>> json_datetime = "1/7/11 9:15" # still encoded as JSON
>>> py_datetime = json.loads(json_datetime) # now decoded to a Python string
>>> datetime.strptime(py_datetime, "%m/%d/%y %I:%M") # coerced into a datetime object
datetime.datetime(2011, 1, 7, 9, 15)
# Now you can save this object to a DateTimeField in a Django model.
If you take a look at https://docs.djangoproject.com/en/dev/ref/models/fields/#datetimefield, it says that django uses the python datetime library which is docomented at http://docs.python.org/2/library/datetime.html.
Here is a working example (with many debug prints and step-by-step instructions:
from datetime import datetime
json_datetime = "1/7/11 9:15"
json_date, json_time = json_datetime.split(" ")
print json_date
print json_time
day, month, year = map(int, json_date.split("/")) #maps each string in stringlist resulting from split to an int
year = 2000 + year #be ceareful here! 2 digits for a year may cause trouble!!! (could be 1911 as well)
hours, minutes = map(int, json_time.split(":"))
print day
print month
print year
my_datetime = datetime(year, month, day, hours, minutes)
print my_datetime
#Generate a json date:
new_json_style = "{0}/{1}/{2} {3}:{4}".format(my_datetime.day, my_datetime.month, my_datetime.year, my_datetime.hour, my_datetime.minute)
print new_json_style