I'm astounded by some code I wrote some time ago. For not entering in much detail i have a method that runs through some objects, wich have a date parameter. If the date parameter is equal to today's date, goes on.
I have set this in my local machine for test and have like 695 objects all with the same date, today, but when the action is run nothing happens, so i debug it to find that my expression date.today() returns datetime.date(2014, 3, 19).
This is is incorrect, as the date of my computer from the date command is Tue Mar 18 20:56:09 AST 2014.
I used from datetime import date. This is one of the more cryptic errors i have ever got. Any experience someone can share here? Thanks a lot.
The method is not timezone aware and there's no platform-independent way to make it so. What is generally done is incorporate something like pytz and call .today() as:
datetime.utcnow().replace(tzinfo = pytz.utc).strftime('%Y-%m-%d')
Related
I'm using Instagram-API-python to create an application. I'm getting a JSON response with below value.
'device_timestamp': 607873890651
I tried to convert this value to readable using python.
import time
readable = time.ctime(607873890651)
print(readable)
It gives following result and seems it is not correct.
Sun Oct 3 16:00:51 21232
I'm not much familiar with the Instagram-API-python. Please someone can help me to solve this problem.
The data is very likely to be incorrect.
Timestamp is a very standard way to store a date-time. Counting the seconds that passed since January 1st, 1970, also known as the UNIX Epoch.
I looked for "Instagram 'device_timestamp'" on Google and all the user-provided values made sense, but yours doesn't.
This is probably an error from the database, it happens.
Use the mentioned ctime conversion, but take the 'taken_at' field if available.
Don't use device_timestamp but use taken_at field. Then taken_at need multiply to 1000.
In Java it looks like this
Date data = new Date(taken_at * 1000);
How to convert relative time that are expressed in humanised words like "-100 days, -6 months, -1 year, +1 year" into YYYY-MM-DD format?
I am posting my answer to help others if they need the same thing.
What I am doing is developing a CLI application, part of the process is user will input starting date and end date, but I want the user to use a relative time like the following:
(for the sake of a an example date, October 23, 2017 would be the current date)
$ cliapp.py --start_time="10 days ago" --end_time="yesterday"
10 days ago is "2017-10-13"
yesterday is "2017-10-22"
$ cliapp.py --start_time="tomorrow"
tomorrow is "2017-10-24"
to accomplish this I found dateparser module and works exactly what I need.
here is the link to it: https://dateparser.readthedocs.io/en/latest/
If you have other solution, feel free to put on comment. :)
I am writing a python code to change the date in linux system to today-1 (dynamically). I tried various combinations but, yet I am not able to succeed. I searched and I found a close proximity to my scenario in this question .
I am able to change the date if I execute the command with static value say:
date --set="$(date +'2013%m%d %H:%M')"
However, I don't want to specify hardcoded value for year i.e., 2013. Instead i want to specify something like "%y-1" i.e.,
date --set="$(date +'%y-1%m%d %H:%M')"
If I run the above command I get the following error
[root#ramesh ~]$ date --set="$(date +'%y-1%m%d %H:%M')"
date: invalid date `14-11016 13:05'
Thanks for your answer. I did not try your approach though, reason being it has to be once again dealt with formatting issues when working with arithmetic operations incase if you want to.
So, I figured out a much simpler and generalized approach
Fetch the previous_year value with this command
date --date='1 years ago'
This gives the previous year date. Now this can be used in the python program to update the system in the following way
"date --set=$(date +'%%y%%m%s %%H:%%M') % previous_year"
This method has few advantages like
I can apply this method for day and month as well like "1 days ago", "1 month ago" along with +%d, +%m, +%y values.
e.g., date --date='1 years ago' +%y
I don't have to worry about the date and month arithmetic calculation logics
date will interpret the %y-1 literally has you showed. What you need is to retrieve the current year, subtract 1 and use this value as the new year.
To get the current_year - 1 you can do:
previous_year=$((`date +'%y'`-1))
echo $previous_year
>>> 13
Now you just need to use this variable to set the new date.
I have a datetime object created from which I subtract 13 days as follow:
(date.today()-timedelta(days=13)).strftime('%Y-%m-%d')
The strangeness occurs when I execute the code at 6AM and 8:30AM. At 6AM, the resulting string is returned as (if today is 2012-02-29):
2012-02-15
which is 14 days before the current! However, running the same line at 8:30AM, the resulting string is returned as:
2012-02-16
Which then correct. So far I have not been able to figure out what the difference is between the small period of time. I use timezone naive datetime objects, if that is important. I would like to know what could cause this change in the resulting string date.
Many thanks.
EDIT: (based on eumiro's suggestion below)
datetime.datetime.now() returns:
>>> datetime.datetime(2012, 2, 29, 10, 46, 20, 659862)
And the timezone is Europe/Vienna on the server and in the django application that runs the line of code.
I also tried running a similar line to the one you suggested:
(pytz.timezone(settings.TIME_ZONE).localize(datetime.now(), is_dst=True) - \
timedelta(days=13)).strftime('%Y-%m-%d')
But with the same results... which is why I think I don't think it has much to do with timezones also. But at the same time not sure where else to look.
You live somewhere in America? This is the place where the timezones are around 6-8 hours behind the UTC and that's the time of UTC midnight.
What does datetime.datetime.now() return?
If you want to get the real local time, use this (replace "America/New_York" with your timezone):
from datetime import datetime, timedelta
import pytz
now = datetime.datetime.now(pytz.timezone("America/New_York"))
dt = (now - timedelta(days=13)).strftime('%Y-%m-%d')
and it should return the same correct values from midnight until midnight.
Unfortunately DST is poorly supported in Python.
Even pytz is not perfect, but can be made to work with hacks.
You have to decide what it means to subtract 2 days from 10th, 1p.m., either 2 calendar days or 48 hours or 172800 seconds.
Totally new to python, I'm actually working on an ex-colleague's script. in looking at it it seems fairly straight-forward. Here's the situation:
The script looks at current localtime (UTC) and renders a time-based table that scrolls/changes throughout the day as the hours pass so there's always a rolling 8 hour table.
The problem is that now we'd like to deploy a copy of this tool (on the same server) in CST ('America/Chicago') (meaning I need to change the UTC time to CST) so I'm just trying to find a way to modify what he has to make the 'current_time' variable == GMT -6.
He used strftime() to get the first hour:
current_time = int(strftime("%H"))
if current_time <19:
temp_page.write(...)
elif current_time == 19:
temp_page.write(...)
etc.
So - from my php knowledge, I'd love to be able to do something like:
current_time = int(strftime("%H"), (localtime() -6 hours))
(yes, I realize that's not real php code, but hopefully you get my meaning ;-))
In my research, I've come across pytz, but this is not installed on the webserver, though I can probably get it if that's the best/easiest way too implement it.
Any help is greatly appreciated.
Yes, try to install pytz, it will help you a lot when working with different timezones (and UTC).
The current UTC time (independent from the timezone of your computer) can be obtained with:
import pytz
from datetime import datetime
now = datetime.now(pytz.utc)
now is now datetime.datetime(2011, 11, 30, 14, 26, 30, 628014, tzinfo=<UTC>) and you can use it to calculate the current UTC hour with now.hour (returns 14)
You could probably use the datetime module (it's part of the standard library, so it's installed if a standard python is on the system).
In particular, datetime objects can have an optional tzinfo attribute, used during timezone conversions. Here's a blog post that explains step-by-step how to use those.