I have a string datetime in YY/M/D/H which is already casted to PST timezone and saved. While reading it I am doing the following
submitted_time = '2020/02/13/11/16'
submitted_datetime = datetime.strptime(submitted_time, '%Y/%m/%d/%H/%M')
This time is already in PST timezone and to calculate the timedifference I tried doing the following :
from pytz import timezone
pacific = timezone('America/Los_Angeles')
today = datetime.now().astimezone(pacific)
But today - submitted_datetime won't work. I get the following error:
*** TypeError: can't subtract offset-naive and offset-aware datetimes
Is there a way I can get this working ? Any help is greatly appreciated.
With the code you provide, I doubt submitted_time will be interpreted as timezone aware, let alone PST. If you do convert it to a timezone aware datetime object, then the substraction works:
from datetime import datetime
from pytz import timezone
submitted_time = datetime.strptime('2020/02/13/11/16', '%Y/%m/%d/%H/%M')
pacific = timezone('America/Los_Angeles')
today = datetime.now().astimezone(pacific)
submitted_time = submitted_time.astimezone(pacific)
print(today - submitted_time)
Output:
5 days, 4:50:57.251801
Related
I am trying to convert the local time into UTC time. But getting the below error.
Error: an integer is required (got type str)
from datetime import datetime
starts_date = '2021-07-30 09:30:00'(timestamp without time zone)
ts = starts_date
x = datetime.utcfromtimestamp(ts)
x_ts = x.timestamp()
Be sure that datetime is imported correctly as from datetime import datetime. Can be a bit confusing but the method utcfromtimestamp belongs to datetime.datetime and not datetime itself.
Here is a working example to convert a timestamp of (now) to a UTC timestamp.
from datetime import datetime as dt
# Create a timestamp object for now.
ts = dt.timestamp(dt.now())
# Convert now to a UTC timestamp.
dt.utcfromtimestamp(ts).timestamp()
>>> 1627637013.657752
datetime.utcfromtimestamp() takes an integer that represent the amount of seconds passed since January 1st 1970.
This means with
from datetime import datetime as dt
print(dt.utcfromtimestamp(0))
you get
1970-01-01 00:00:00
I importing this python modules
from datetime import date, timedelta, datetime
to_date = date.today()
from_date = to_date - timedelta(days=2)
print(f"Local Date and Time {datetime.datetime.now()}")
when I run this code I'm getting error like this_
type object 'datetime.datetime' has no attribute 'datetime'
Can anyone please tell how can I solve this problem.
The import line from datetime import date, timedelta, datetime means you imported
datetime.datetime access with datetime,
datetime.date access with date
datetime.timedelta with timedelta
So as you did for date and timedelta, now() is a method of datetime class and not datetime package :
to_date = date.today()
from_date = to_date - timedelta(days=2)
print(f"Local Date and Time {datetime.now()}") # not datetime.datetime.now()
See the basic example:
import datetime
x = datetime.datetime.now()
print(x)
I think you have put datetime 2 times wrongly. Since you are already importing datetime, it should be like this:
print(f"Local Date and Time {datetime.now()}")
I have to create a code that can tell me the current time in any city (as a variable) and print the utc offset between that time and utc. I already have the following code which gives the current time and the offset from a timezone, but this timezone is not always utc. Note: the city names are stored in a text file and the user should be able to add and remove any city. I am using tkinter for the gui.
from datetime import datetime, timedelta
from pytz import timezone
import pytz
def tz():
utc = pytz.utc
amsterdam = timezone('Europe/Amsterdam')
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
loc_dt = utc.localize(datetime.today())
tz = loc_dt.astimezone(amsterdam)
print(tz.strftime(fmt))
The file contents are as follows:
Amsterdam
Brasilia
Los Angeles
Abu Dhabi
Tokyo
Singapore
Can someone please help me with an easy code to do this? Thank you in advance
You're using pytz already, so I'd go for:
from datetime import datetime
from pytz import timezone, all_timezones
def to_timezone(dt, tz):
assert dt.tzinfo is not None
assert tz in all_timezones
return dt.astimezone(timezone(tz))
print to_timezone(datetime.now(timezone('UTC')), 'Europe/Amsterdam')
I set it to UTC by default but the point is:
have a non naive datetime
convert it
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.
I wanted to create a string time in to offset-aware timezone for comparing with another offset-aware datetime.
from datetime import datetime, timedelta
from dateutil import parser
from dateutil.tz import gettz
today = datetime.now(gettz()) # creating a offset-aware timezone, I wanted to create manual string time also in this format
new_date = parser.parse('Apr 1 2014') # I wanted this output to be converted into offset-aware timezone
output of today variable is = 2014-04-30 07:54:26.500678+05:30
output of new_date variable is = 2014-04-01 00:00:00 ( need to convert this into above format )
any other method for converting this ?