I have a datetime filed in my models.py and another field that saves the selected timezone as well (like Asia/Tehran).
I need to append the the utc info of this timezone to my datetime object like this:
'20/4/2021 18:33:00 Gmt+4:30
How can i do that?
Use this code, replace the numbers with your specified date in your GMT+4.5 timezone.
import datetime
timezone_diff = datetime.timedelta(hours=4.5)
GMT_timezone = datetime.timezone(timezone_diff, name="GMT")
GMT_time = datetime.datetime(2017,2,14,12,15,1,99,GMT_timezone,fold=1)
print('{0:%d}/{0:%m}/{0:%Y} {0:%H:%M:%S} {0:%Z}{0:%z}'.format(GMT_time))
See results:
Related
I have a question related to dates and time in Python.
Problem:
date = datetime.datetime.strptime(str(row[1]), "%Y-%m-%d %H:%M:%S")
localtime = date.astimezone(pytz.timezone("Europe/Brussels"))
formattedDate = localtime.strftime("%Y-%m%-%d")
In the code above, str(row[1]) gives back a UTC datetime coming from a mysql database: 2022-02-28 23:00:00
I parse this as a datetime and change the timezone to Europe/Brussels.
I then format it back to a string.
Expected result:
I'd like to return the date in local time. Europe/Brussels adds one hour so I would expect that strftime returns 2022-03-01, but it keeps returning 2022-02-28.
Can somebody help?
date is a naïve date, without timezone, because no timezone information was in the string you parsed. Using astimezone on that simply attaches timezone information to it, turning a naïve date into an aware one. It obviously can't convert any times, because it doesn't know what to convert from.
This also already contains the answer: make the date aware that it's in UTC first before trying to convert it to a different timezone:
date = datetime.datetime.strptime(...).astimezone(datetime.timezone.utc)
Ah, I see!
I ended up doing this, basically the same as you mentioned:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('Europe/Brussels')
utcdate = datetime.datetime.strptime(str(row[1]), "%Y-%m-%d %H:%M:%S")
utcdate = utcdate.replace(tzinfo=from_zone)
localdate = utcdate.astimezone(to_zone)
formattedLocalDate = localdate.strftime("%Y%m%d");
The naïve date gets UTC aware by the utcdate.replace(tzinfo=from_zone).
Thanks for helping!
I would LIKe to know how to set a specific DateTime timestamp using the DateTime module in python. For example if I want ... To happen on 1 August 2022. How can I make a DateTime timestamp that will hold that date. Thanks for all help in advance
You can construct a new datetime object with your date (and optionally with time) and then call timestamp() on it.
For example, you can do:
from datetime import datetime
timestamp = datetime(2022, 8, 1).timestamp()
# timestamp is now 1659304800.0
You can find the official documentation here.
To create a date, we can use the datetime() class (constructor) of the datetime module.
The datetime() class requires three parameters to create a date: year, month, day.
Example
Create a date object:
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
source
I need to assign to a variable the current datetime string in isoformat like the following:
2018-09-27T16:19:16+02:00
What I'm doing is:
import datetime
....
print(datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat())
But this is going to print the string with utc tz:
2018-09-28T07:05:35+00:00
Not clear yet to me what's the clean way I should change tzinfo param to set wanted tz to UTC+02:00 ?
Thanks
utcnow() already gives you the the time at +00:00, if you'd like to recieve the time at a specific timezone, you should provide the timezone as an argument to now([tz]).
https://docs.python.org/3/library/datetime.html
>>> import datetime as dt
>>> dt.datetime.now(tz = dt.timezone(offset = dt.timedelta(hours = 2))).replace(microsecond = 0).isoformat()
'2018-09-28T09:20:19+02:00'
Consider a list of posix time stamps
posix_times = [1490750889, 1490751209, 1490751569]
I would like to convert each element in the array to a text string containing the local date and time in the US/Pacific time zone:
["3/28/2017 18:28:09", "3/28/2017 18:33:29", "3/28/2017 18:39:29"]
What is the simplest way to do this which requires a minimum of package imports?
A related problem was addressed in Converting unix timestamp string to readable date in Python, which offers, for example a solution of the form:
posix_time = 1490750889
datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')
which does not offer the explicit ability to convert this time to another time zone. Also, it appears that such a method does not work on lists and would require a for loop/list comprehension.
You can do this with the standard datetime library:
In [1]: import datetime
In [2]: posix_times = [1490750889, 1490751209, 1490751569]
In [3]: [datetime.datetime.fromtimestamp(x).strftime("%x %X") for x in posix_times]
Out[3]: ['03/28/17 20:28:09', '03/28/17 20:33:29', '03/28/17 20:39:29']
You can convert a UNIX timestamp into a datetime object and then format it using its strftime method. However, this will give you a timezone-unaware datetime. In order to make it timezone-aware, you'll need to get the timezone from pytz and use the localize method:
from datetime import datetime
from pytz import timezone
# ...
def format_time(time, tz):
localized = tz.localize(datetime.fromtimestamp(time))
return localized.strftime('%d/%m/%Y %H:%M:%S')
us_pacific = timezone('US/Pacific')
dates = map(lambda t: format_time(t, us_pacific), posix_times)
In the model there is a field DateTimeField(), the database stores the value of the form 2015-09-21 17:37:11. How to make a selection, for the last several hours. For example, in the sample were only the values for the last 3 hours.
You need to build the date reference manually, and use it in the query.
from datetime import datetime, timedelta
now = datetime.now()
before = now - timedelta(hours=3)
qs = MyModel.objects.filter(date__gte=before)
As a reference, the datetime module.
Note that if you use locale-aware times in your application (through USE_TZ=True setting), you will need to change the way you get current time to this:
from django.utils import timezone
now = timezone.now()
Try:
from datetime import datetime, timedelta
delta = datetime.now() - timedelta(hours=3)
Model.objects.filter(date_time__gte=delta)