So I'm trying to prepare a message with Python that takes a Timestamp, but I'm having trouble converting a datetime to a protobuf Timestamp.
Here's what I've tried so far:
from google.protobuf.timestamp_pb2 import Timestamp
import datetime
now = datetime.datetime.now()
timestamp = Timestamp()
timestamp.FromDatetime(now)
However, I'm getting an error AttributeError: 'Timestamp' object attribute 'seconds' is read-only
How can I create a Timestamp from a datetime?
This code is working fine on my machine
from google.protobuf.timestamp_pb2 import Timestamp
import datetime
now = datetime.datetime.now()
timestamp = Timestamp()
timestamp.FromDatetime(now)
Output:
seconds: 1591859232
nanos: 803377000
Related
I need to filter the lines where the date is today and not more than 2 hours ago according to local time (the code needs to be malleable as I travel to different timezones):
from tzlocal import get_localzone
import pandas as pd
import pytz
df['DATA_HORA'] = df.apply(lambda x: datetime.strptime(f'{x["DATA"]} {x["HORA"]}', '%d/%m/%Y %H:%M'), axis=1)
local_tz = get_localzone()
local_tz = pytz.timezone(local_tz.zone)
df_today = df[(df['DATA_HORA'].dt.tz_localize(local_tz) >= (datetime.now(local_tz) - timedelta(hours=2))) & (df['DATA_HORA'].dt.date == datetime.now(local_tz).date())]
I tried to understand how to do it, according to the specific documentation about it:
https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html#getting-a-time-zone-s-name
But I was not successful, how should I proceed to find my local timezone and not receive this warning anymore?
tzlocal.get_localzonealready returns a timezone object, which you can use directly:
import pandas as pd
from tzlocal import get_localzone
z = get_localzone()
print(repr(z))
# _PytzShimTimezone(zoneinfo.ZoneInfo(key='Europe/Berlin'), 'Europe/Berlin')
print(pd.Timestamp("now", tz=z))
# 2023-02-14 17:54:32.445179+01:00
You can also unwrap it and obtain the string representation in a way that doesn't trigger warnings:
print(repr(z.unwrap_shim()))
# zoneinfo.ZoneInfo(key='Europe/Berlin')
print(z.unwrap_shim().key)
# Europe/Berlin
...or also like
from tzlocal import get_localzone_name
print(get_localzone_name())
# Europe/Berlin
Note that if you use pandas, you neither need the datetime module nor pytz here.
I am trying to delete 3 years old data in my python django db. Here is code:
from datetime import datetime
from dateutil.relativedelta import relativedelta
def db_cleanup():
cleanup_start = datetime.utcnow().date()
three_years_ago = cleanup_start - relativedelta(years=3)
MyData.objects.filter(create_date__lt=three_years_ago).delete()
however I receive RuntimeWarning: DateTimeField received a naive datetime . How to do it properly?
Use timezone.now() to create an aware datetime then reset time to midnight but keep a datetime object (not date):
from django.utils import timezone
from dateutil.relativedelta import relativedelta
def db_cleanup():
cleanup_start = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
three_years_ago = cleanup_start - relativedelta(years=3)
MyData.objects.filter(create_date__lt=three_years_ago).delete()
I get the following publishedAt string '2021-08-24T11:00:19Z' from youtube's api for the video object. But I don;t understand how to convert it into a datetime object and find the hours between it and current.
I tried the below code but it didn't work
view.py
from django.utils import timezone
from datetime import datetime
today = timezone.now()
publishedAt = datetime.fromtimestamp('2021-08-24T11:00:19Z')
daysOld = (today - publishedAt).days
But I am getting the below error at this line publish_date = datetime.fromtimestamp('2021-08-24T11:00:19Z')
TypeError: an integer is required (got type str)
I don't understand how to convert the string to datetime object and get the difference.
The string you provide here is datetime formatted by the ISO 8601 standard [wiki]. You can parse this with the parser.isoparse(…) method [Python-doc] from the dateutil package:
>>> from dateutil.parser import isoparse
>>> isoparse('2021-08-24T11:00:19Z')
datetime.datetime(2021, 8, 24, 11, 0, 19, tzinfo=tzutc())
You thus can install the package with:
pip3 install python-dateutil
and then run this with:
from django.utils import timezone
from dateutil.parse import isoparse
today = timezone.now()
publish_date = isoparse('2021-08-24T11:00:19Z')
diff = today - publish_date
Here is my Transaction class:
class Transaction(object):
def __init__(self, company, num, price, date, is_buy):
self.company = company
self.num = num
self.price = price
self.date = datetime.strptime(date, "%Y-%m-%d")
self.is_buy = is_buy
And when I'm trying to run the date function:
tr = Transaction('AAPL', 600, '2013-10-25')
print tr.date
I'm getting the following error:
self.date = datetime.strptime(self.d, "%Y-%m-%d")
AttributeError: 'module' object has no attribute 'strptime'
How can I fix that?
If I had to guess, you did this:
import datetime
at the top of your code. This means that you have to do this:
datetime.datetime.strptime(date, "%Y-%m-%d")
to access the strptime method. Or, you could change the import statement to this:
from datetime import datetime
and access it as you are.
The people who made the datetime module also named their class datetime:
#module class method
datetime.datetime.strptime(date, "%Y-%m-%d")
Use the correct call: strptime is a classmethod of the datetime.datetime class, it's not a function in the datetime module.
self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")
As mentioned by Jon Clements in the comments, some people do from datetime import datetime, which would bind the datetime name to the datetime class, and make your initial code work.
To identify which case you're facing (in the future), look at your import statements
import datetime: that's the module (that's what you have right now).
from datetime import datetime: that's the class.
I got the same problem and it is not the solution that you told. So I changed the "from datetime import datetime" to "import datetime". After that with
the help of "datetime.datetime" I can get the whole modules correctly. I guess this is the correct answer to that question.
Values may differ depending on usage.
import datetime
date = datetime.datetime.now()
date.strftime('%Y-%m-%d') # date variable type is datetime
The value of the date variable must be a string::
date = '2021-09-06'
datetime.datetime.strptime(date, "%Y-%m-%d")
str(datetime.datetime.strptime(date, "%Y-%m-%d")) # show differently
The solutions mentioned by the others are correct. But for me, it was a problem with another library importing datetime module for me and overriding the datetime class I was importing.
an example with tsai library:
from datetime import datetime
from tsai.all import *
This will give you the error: 'module' object has no attribute 'strptime'.
In this case, just flip the order of imports or just don't import everything (even if the documentation does that) :
from tsai.all import *
from datetime import datetime
I'm trying to list out tweets with their time-stamps. I have this...
#!/usr/bin/python
import twitter
api = twitter.Api()
statuses = api.GetUserTimeline('ttytter')
for s in statuses:
print s.created_at + " " + s.text
Which prints out...
Sat Oct 20 04:56:47 +0000 2012 #uriel1998 W/r/t DMs, they appear just fine in 2.0.4 and 2.1 beta here, near as I can tell.
Which is pretty much what I'm after, but for the time, which seems to be in the wrong timezone. https://twitter.com/ttytter/status/259518502069760000
Is there a way I can change this within the python-twitter library? I was looking at GetTimeZone() and SetTimeZone(), but I haven't been able to figure out how they work.
Also looking at how to shift a datetime object by 12 hours in python but not sure if I need to go there.
Thanks for any help!
python-twitter returns the status timestamps as a string and as the number of seconds since the epoch. The latter is the simplest to convert to a timezone-aware datetime instance (see this answer).
Unfortunately the user's time_zone attribute is not in the standard tz database format used by pytz, so it is necessary to use the utc_offset user attribute instead (we still use the time_zone attribute to name the tzinfo created with with the UTC offset). The python-dateutil package provides a convenience type tzoffset that allows the creation of tzinfo instances from UTC offsets, which we can then use to convert the datetime from UTC to the local time zone:
import pytz
import twitter
from datetime import datetime
from dateutil.tz import tzoffset
USERNAME = 'ttytter'
api = twitter.Api()
# get a 'tzinfo' instance with the UTC offset for the user's local time
user = api.GetUser(USERNAME)
localtime_tz = tzoffset(user.time_zone, user.utc_offset)
statuses = api.GetUserTimeline(USERNAME)
for s in statuses[:1]:
# get UTC timestamp from seconds since epoch
utc_dt = datetime.utcfromtimestamp(s.created_at_in_seconds).replace(tzinfo=pytz.utc)
print('utc: {}'.format(utc_dt))
# convert to local time in the user's timezone
localtime_dt = utc_dt.astimezone(localtime_tz)
print('localtime [{}]: {}'.format(localtime_dt.tzname(), localtime_dt))
which gives the output for the first status:
utc: 2012-10-20 04:56:47+00:00
localtime [Pacific Time (US & Canada)]: 2012-10-19 20:56:47-08:00
Combining suggestions from Pedro Romano and J.F. Sebastian, I have this...
import pytz
import twitter
from datetime import datetime
USERNAME = 'ttytter'
api = twitter.Api()
user = api.GetUser(USERNAME)
pst_tz = pytz.timezone('America/Los_Angeles')
statuses = api.GetUserTimeline(USERNAME)
for s in statuses[:1]:
# get UTC timestamp from seconds since epoch
utc_dt = datetime.utcfromtimestamp(s.created_at_in_seconds).replace(tzinfo=pytz.utc)
# convert to given timezone
pst_dt = pst_tz.normalize(utc_dt.astimezone(st_tz))
print(pst_dt.strftime('%Y-%m-%d %H:%M:%S ')) + s.text
Output: 2012-10-19 21:56:47 #uriel1998 W/r/t DMs, they appear just fine in 2.0.4 and 2.1 beta here, near as I can tell. which is the correct time zone and also accounts for DST.
Thank you!