Python string to Django timezone (aware datetime) - python

TL;DR;
How to convert 2016-01-01 to Django timezone?
Full version:
I receive a query string parameter from a form and I wanna get that string and use it as a datetime filter in Django.
The problem is that when I convert the string to a datetime, it's not making an aware datetime and so I lose a few hours due to timezone different. Maybe I'm losing myself in the formatting, but I'm not being able to do it.
I have pytz, I have USE_TZ = True in my settings as well.
example:
from datetime import date
# Example from what I receive as GET querystring parameter
start_date, end_date = '15-01-2016', '16-01-2016'
DATE_FORMAT = '%Y-%m-%d'
start_date = start_date.split('-')
start_date = date(int(start_date[2]), int(start_date[1]), int(start_date[0]))
sd_filter = start_date.strftime(DATE_FORMAT)
end_date = end_date.split('-')
end_date = date(int(end_date[2]), int(end_date[1]), int(end_date[0]))
ed_filter = end_date.strftime(DATE_FORMAT)
#query
my_list = MyModel.objects.filter(created_at__range=(sd_filter, ed_filter))
the problem lies in the filter. I'm losing a few hours due to timezone from Django settings.
UPDATE: I don't need to convert a datetime.now() to my time. I need to convert a string to datetime.

I know this is old but maybe will be helpful since I got into this situation as well:
What about using make_aware() ?
from datetime import datetime
from django.utils.timezone import make_aware
date = '22-05-2018'
aware = make_aware(datetime.strptime(date, '%d-%m-%Y'))
This will use the currently active timezone (activated by timezone.activate). If no timezone is activated explicitly, it would use the default timezone -- TIME_ZONE specified in settings.py.

You are comparing time-zone unaware Python Date objects with the time-zone aware DateTimeField fields in your database. It is probably more intuitive to use DateTime objects - and these can be made time-zone aware easily as follows:
import datetime
import pytz
start_date = '15-01-2016'
end_date = '16-01-2016'
date_format = '%d-%m-%Y'
unaware_start_date = datetime.datetime.strptime(start_date, date_format)
aware_start_date = pytz.utc.localize(unaware_start_date)
unaware_end_date = datetime.datetime.strptime(end_date, date_format)
aware_end_date = pytz.utc.localize(unaware_end_date)
my_list = MyModel.objects.filter(created_at__range=(aware_start_date, aware_end_date))
This creates unaware_start_date and unaware_end_date DateTime objects using strptime(). It then uses pytz.utc.localize to make the objects time-zone aware (you will need to replace utc with your relevant time-zone).
You can then have time-zone aware DateTime objects - aware_start_date and aware_end_date. Feeding these into your filter should yield the desired results.

from django.utils import timezone
timestamp_raw = timezone.now() #current time, or use whatever time you have
date_format = '%Y-%m-%d %H:%M:%S' #time format day-month-year hour:minutes:seconds
timestamp = timezone.datetime.strftime(timestamp_raw, date_format)
Or Using the new f-string formatter
f"{timezone:%Y-%m-%d %H:%M:%S %p}"

Related

How to format a date value for Hubspot API using Python

I have read the docs saying that to pass the value for a Hubspot date field you should format your Date as midnight UTC. However, I've had no luck doing so in Python. I assume I am just missing the magic Python incantation that will get the right result. Here is what I have:
from pytz import timezone, utc
from hubspot.crm.contacts import SimplePublicObject,
created_dt = # datetime from sqlalchemy query
utcdt = utc.localize(
datetime(
year=created_dt.year,
month=created_dt.month,
day=created_dt.day
)
)
ts = int(utcdt.timestamp())
props = SimplePublicObjectInput({"last_booking": str(ts)})
return client.crm.companies.basic_api.update(
hs_id, simple_public_object_input=props
)
this returns this error:
{"status":"error",
"message":"Property values were not valid: [{\"isValid\":false,\"message\":\"1570233600 is at 4:10:33.600 UTC, not midnight!\"...
}
Ah, the answer was right there. Python timestamp returns the time in seconds, and HubSpot expects milliseconds. I just had to multiply by 1000:
ts = int(utcdt.timestamp()*1000)
now all looks good.
did you try adding hours and minutes to your datetime call
datetime(
year=created_dt.year,
month=created_dt.month,
day=created_dt.day,
hour=0,
minute=0
)
Use the Hubspot supported "sanetime" module: https://github.com/HubSpot/sanetime
Then to get a date:
yourdate = datetime.datetime.date()
hubspot_date = sanetime.time(yourdate )
Or if you do not want a dependency:
#convert datetime to UTC
your_utc_datetime = your_datetime.astimezone(pytz.UTC)
#replace time with midnight
your_utc_date_midnight = your_utc_datetime.replace(hour=0,minute=0,second=0, microsecond=0)
# convert to epoch (Python 3.3+)
your_hubspot_date = your_utc_date_midnight.timestamp()*1000

Converting to unix timestamp Python

I am trying to convert a datestamp of now into Unix TimeStamp, however the code below seems to be hit but then just jumps to the end of my app, as in seems to not like the time.mktime part.
from datetime import datetime
import time
now = datetime.now()
toDayDate = now.replace(hour=0, minute=0, second=0, microsecond=0)
newDate = time.mktime(datetime.strptime(toDayDate, "%Y-%m-%d %H:%M:%S").timetuple())
print(newDate)
Change
newDate = time.mktime(datetime.strptime(toDayDate, "%Y-%m-%d %H:%M:%S").timetuple())
to
newDate = time.mktime(datetime.timetuple())
as an example I did:
from datetime import datetime
from time import mktime
t = datetime.now()
unix_secs = mktime(t.timetuple())
and got unix_secs = 1488214742.0
Credit to #tarashypka- use t.utctimetuple() if you want the result in UTC (e.g. if your datetime object is aware of timezones)
You could use datetime.timestamp() in Python 3 to get the POSIX timestamp instead of using now().
The value returned is of type float. timestamp() relies on datetime which in turn relies on mktime(). However, datetime.timestamp() supports more platforms and has a wider range of values.

'datetime.datetime' object has no attribute 'read'

Users in my app have date_joined fields that are in this format: 2014-12-14 14:46:43.379518+00:00
In order to pass this datetime along to Intercom.io, it must be a UNIX timestamp like this: 1426020706 (this is not the same time, just an example).
I've tried several methods I've read here on Stack Overflow (nothing in this question has the same starting time format: Converting datetime.date to UTC timestamp in Python), but none have worked. mktime() seemed promising, but I got "'datetime.datetime' object has no attribute 'mktime'."
I just tried this:
import time
import dateutil.parser
import member.models import Member
member = Member.objects.get(email="aspeksnijder#outlook.com")
date_joined = member.date_joined
dt = dateutil.parser.parse(date_joined)
print int(time.mktime(dt.timetuple()))
It returned "'datetime.datetime' object has no attribute 'read'". How can I accomplish this?
It seems you have an aware datetime object. If you print it then it looks like:
2014-12-14 14:46:43.379518+00:00
To be sure print(repr(date_joined)).
Converting datetime.date to UTC timestamp in Python shows several ways how you could get the timestamp e.g.,
timestamp = date_joined.timestamp() # in Python 3.3+
Or on older Python versions:
from datetime import datetime
# local time = utc time + utc offset
utc_naive = date_joined.replace(tzinfo=None) - date_joined.utcoffset()
timestamp = (utc_naive - datetime(1970, 1, 1)).total_seconds()
Note: timestamp = calendar.timegm(date_joined.utctimetuple()) would also work in your case but it may return a wrong result silently if you pass it a naive datetime object that represents local time by mistake.
If your input is a time string then convert the time string into a datetime object first.
What about (using the dateutil and pytz packages):
import dateutil.parser
from datetime import datetime
import calendar
import pytz
def str2ts(s):
''' Turns a string into a non-naive datetime object, then get the timestamp '''
# However you get from your string to datetime.datetime object
dt = dateutil.parser.parse(s) # String to non-naive datetime
dt = pytz.utc.normalize(dt) # Normalize datetime to UTC
ts = calendar.timegm(dt.timetuple()) # Convert UTC datetime to UTC timestamp
return int(ts)
def ts2str(ts):
'''Convert a UTC timestamp into a UTC datetime, then format it to a string'''
dt = datetime.utcfromtimestamp(ts) # Convert a UTC timestamp to a naive datetime object
dt = dt.replace(tzinfo=pytz.utc) # Convert naive datetime to non-naive
return dt.strftime('%Y-%m-%d %H:%M:%S.%f%z')
Which we can test with:
# A list of strings corresponding to the same time, with different timezone offsets
ss = [
'2014-12-14 14:46:43.379518+00:00',
'2014-12-14 15:46:43.379518+01:00',
'2014-12-14 16:46:43.379518+02:00',
'2014-12-14 17:46:43.379518+03:00',
]
for s in ss:
ts = str2ts(s)
s2 = ts2str(ts)
print ts, s2
Output:
1418568403 2014-12-14 14:46:43.000000+0000
1418568403 2014-12-14 14:46:43.000000+0000
1418568403 2014-12-14 14:46:43.000000+0000
1418568403 2014-12-14 14:46:43.000000+0000
These output all the same timestamps, and "verification" formatted strings.
You can try the following Python 3 code:
import time, datetime
print(time.mktime(datetime.datetime.strptime("2014-12-14 14:46:43.379518", '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=datetime.timezone.utc).timetuple()))
which prints:
1418568403.0
I had that problem when I used input from Django's DateField, which is displayed in a form of XXXX-YY-ZZ: parse(django_datefield) causes the exception.
The solution: use str(django_datefield).
parse(str(django_datefield))
I know this is an old post, but I want to highlight that the answer is likely what #Peter said in his comment:
It looks like member.date_joined is already a datetime object, and there's no need to parse it. – Peter Feb 25 '17 at 0:33
So-- your model probably already parses into a datetime.datetime object for you.

Python Convert time to UTC format

from django.utils import timezone
time_zone = timezone.get_current_timezone_name() # Gives 'Asia/Kolkata'
date_time = datetime.time(12,30,tzinfo=pytz.timezone(str(time_zone)))
Now I need to convert this time to UTC format and save it in Django model. I am not able to use date_time.astimezone(pytz.timezone('UTC')). How can I convert the time to UTC. Also Back to 'time_zone'.
This is a use case when user type time in a text box and we need to save time time in UTC format. Each user will also select his own time zone that we provide from Django timezone module.
Once the user request back the saved time it must be shown back to him in his selected time zone.
These things are always easier using complete datetime objects, e.g.:
import datetime
import pytz
time_zone = pytz.timezone('Asia/Kolkata')
# get naive date
date = datetime.datetime.now().date()
# get naive time
time = datetime.time(12, 30)
# combite to datetime
date_time = datetime.datetime.combine(date, time)
# make time zone aware
date_time = time_zone.localize(date_time)
# convert to UTC
utc_date_time = date_time.astimezone(pytz.utc)
# get time
utc_time = utc_date_time.time()
print(date_time)
print(utc_date_time)
print(utc_time)
Yields:
2014-07-13 12:30:00+05:30
2014-07-13 07:00:00+00:00
07:00:00
right now for me.
set the timezone to UTC in your settings.py. Get the user input of time and timezone in certain format. Suppose you get the user time as 'Jul-7-2014 12:35PM:30' (consider using date input in your html).
from datetime import datetime, timedelta
// convert the time to standard format
user_date = datetime.strptime('Jul-7-2014 12:35PM:30', '%b-%d-%Y %I:%M%p:%S')
user_date_string = user_date.strftime('%Y-%m-%d %H:%M:%S')
// save the time to model with users timezone
// now when user asks back for his time, add the timezone with timedelta
user_date = datetime.strptime(user_date_string, '%Y-%m-%d %H:%M:%S')
user_date = user_date + timedelta(hours = 5, minutes = 30)
// finally display it
print user_data.strftime('%Y-%m-%d %H:%M:%S')
*this is not considering django inbuild datetime functions which returns datetime object for datetime model field. If implemented that it will be more simple

pytz and astimezone() cannot be applied to a naive datetime

I have a date and I need to make it time zone aware.
local_tz = timezone('Asia/Tokyo')
start_date = '2012-09-27'
start_date = datetime.strptime(start_date, "%Y-%m-%d")
start_date = start_date.astimezone(local_tz)
now_utc = datetime.now(timezone('UTC'))
local_now = now_utc.astimezone(local_tz)
I need to find if this is true:
print start_date>local_now
But I get this error.
start_date = start_date.astimezone(local_tz)
ValueError: astimezone() cannot be applied to a naive datetime
I convert utc to tokyo with no issue. I need to make start_date timezone aware ad well in tokyo.
Thanks
For pytz timezones, use their .localize() method to turn a naive datetime object into one with a timezone:
start_date = local_tz.localize(start_date)
For timezones without a DST transition, the .replace() method to attach a timezone to a naive datetime object should normally also work:
start_date = start_date.replace(tzinfo=local_tz)
See the localized times and date arithmetic of the pytz documentation for more details.
You could use local_tz.localize(naive_dt, is_dst=None) to convert a naive datetime object to timezone-aware one.
from datetime import datetime
import pytz
local_tz = pytz.timezone('Asia/Tokyo')
start_date = local_tz.localize(datetime(2012, 9, 27), is_dst=None)
now_utc = datetime.utcnow().replace(tzinfo=pytz.utc)
print start_date > now_utc
is_dst=None forces .localize() to raise an exception if given local time is ambiguous.
If you are using Django Rest Framework you could override the DateTimeField class like:
class DateTimeFieldOverridden(serializers.DateTimeField):
def to_representation(self, value):
local_tz = pytz.timezone(TIME_ZONE)
value = local_tz.localize(value)
return super(DateTimeFieldOverridden, self).to_representation(value)
And you use it like this in your serializer:
date_time = DateTimeFieldOverridden(format='%d-%b-%Y', read_only=True)
Hope this helps someone.

Categories

Resources