I ran when it was noon in turkey..this is what I got:
2017-12-22 20:11:46.038218+03:00
import pytz
from pytz import timezone
from datetime import datetime
utc_now = datetime.now()
utc = pytz.timezone('UTC')
aware_date = utc.localize(utc_now)
turkey = timezone('Europe/Istanbul')
now_turkey = aware_date.astimezone(turkey)
Why did I get 20:11:46?
Because the base time is wrong, just change utc_now = datetime.now() to utc_now = datetime.utcnow() and then it works.
As #RemcoGerlich has said, you should use utcnow to get UTC.
Whole code:
import pytz
from pytz import timezone
from datetime import datetime
utc_now = datetime.utcnow()
utc = pytz.timezone('UTC')
aware_date = utc.localize(utc_now)
turkey = timezone('Europe/Istanbul')
now_turkey = aware_date.astimezone(turkey)
Related
i wanted to write a code that executes a function at a specific time but...
it keeps running the code immediately i tried 6 different ways to code it but they all failed
i will past the code below
first i tried
import schedule
import time
import m5
def run_f5():
m5.runF5()
schedule.every().day.at("02:05").do(run_f5)
while True:
schedule.run_pending()
time.sleep(1)
#this code was supposed to run 5 mins from now but it ran immediately
then i tried
import datetime
import time
import m5
while True:
current_time = datetime.datetime.now()
if current_time.hour == 2 and current_time.minute == 12:
m5.runF5()
time.sleep(60)
#this code was supposed to run 5 mins from now but it ran immediately
then i tried
import datetime
import time
import m5
while True:
current_time = datetime.datetime.now()
if current_time.hour == 2 and current_time.minute == 24:
m5.runF5()
time.sleep(60)import datetime
import time
import m5
while True:
current_time = datetime.datetime.now()
if current_time.hour == 2 and current_time.minute == 24:
m5.runF5()
time.sleep(60)
same result the code ran immediately then i tried
import datetime
import time
import m5
# Get the current time
current_time = datetime.datetime.now()
# Create a datetime object for the desired time
desired_time = datetime.datetime(current_time.year, current_time.month, current_time.day, 2, 59)
# Check if the desired time has passed for today
if desired_time < current_time:
# If it has, set the desired time to tomorrow
desired_time += datetime.timedelta(days=1)
# Calculate the time difference between the current time and the desired time
time_diff = desired_time - current_time
# Sleep for the time difference
time.sleep(time_diff.total_seconds())
#Run your function
m5.runF5()
same the code ran immediately then i tried
import datetime
import time
import m5
while True:
current_time = datetime.datetime.now()
if current_time.hour == 3 and current_time.minute == 30:
m5.runF5()
break
time.sleep(60)
i tried the followed 3 codes but failed each time
import datetime
import time
import m5
current_time = datetime.datetime.now()
# Create a datetime object for the desired time
desired_time = datetime.datetime(current_time.year, current_time.month, current_time.day, 3, 40)
# Check if the desired time has passed for today
if desired_time < current_time:
# If it has, set the desired time to tomorrow
desired_time += datetime.timedelta(days=1)
# Calculate the time difference between the current time and the desired time
time_diff = desired_time - current_time
# Sleep for the time difference
time.sleep(int(time_diff.total_seconds()))
#Run your function
m5.runF5()
then
import datetime
import time
import m5
# Create a datetime object for the desired time
desired_time = datetime.datetime(current_time.year, current_time.month, current_time.day, 3, 56)
while True:
current_time = datetime.datetime.now()
if current_time >= desired_time:
break
time.sleep(1)
# Run your function
m5.runF5()
import schedule
import time
import m5
def run_at_specific_time():
m5.runF5()
# Schedule the function to run every day at 04:10 AM
schedule.every().day.at("12:00").do(run_at_specific_time)
while True:
schedule.run_pending()
time.sleep(1)
plz help i have ran out of ideas and have no clue why any of the above run at once and not at the specific time
i am importing the code from a separate file maybe that is causing some issues
Here is the code (only this):
import pytz
from time import sleep
from datetime import datetime
dt_format = "%H:%M"
tz = pytz.timezone('Asia/Riyadh')
jt = datetime.now(tz)
time_now = (jt.strftime(dt_format))
time = time_now.replace(":","")
timed1 = (int("1530")) #the time in 24h format
while True:
#print('azan on')
if timed1 == time_now:
print(time_now)
print(timed1)
print ("its the time")
sleep (90)
I tried to keep the format normal (15:30) but still the same.
(replace) not required you can delete if so.
You just have to update the time and put it in the loop and it will work , thanks to #MatsLindh (check comments)
I have this code right here that I'm making a report, and I'm trying to work with the date but I cant cause pycharm says it cant work with "series" format, I`m trying to convert it to simple datetime but nothing works, can u guys help me?
the "DATA" is coming with the format of "datetime n 64" and I need it to be normal datetime, how can I do this?
import pyodbc
import pandas as pd
import matplotlib.pyplot as plt
import datetime
class generate_report():
def __init__(self):
self.csv = "output.csv"
self.sql_conn = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',
server = 'localhost', database = 'MPWJ_BI')
self.query = "select * from CTP_EXTRATO_GERAL where HISTORICO = 'Aplicação' order by data"
self.df = pd.read_sql(self.query, self.sql_conn)
self.df['DATA'] = pd.to_datetime(self.df['DATA'])
self.df.to_csv(self.csv)
def analyze_data(self):
pd.read_csv(self.csv)
print(self.df.dtypes)
It depends on how your date looks like
for example
from datetime import datetime
datetime_object = datetime.strptime('Jun 1 2020 7:31PM', '%b %d %Y %I:%M%p')
documentation
https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime
EDIT:
To convert from datetime64 to datetime you can do the following:
import datetime
import numpy as np
# Current time UTC
dt = datetime.datetime.utcnow()
# Convert to datetime64
dt64 = np.datetime64(dt)
# convert to epoch
ts = (dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's')
# Convert to datetime
print(datetime.datetime.fromtimestamp(ts))
I'm trying to change the date of launch time for EC2 instances in AWS to something more friendly using Python 3.
The error that I'm getting says:
datetime(launch_time)
TypeError: 'module' object is not callable
My program is doing this:
import boto3
import time
import datetime
instance_id = 'i-024b3382f94bce588'
instance = ec2.describe_instances(
InstanceIds=[instance_id]
)['Reservations'][0]['Instances'][0]
launch_time = instance['LaunchTime']
datetime(launch_time)
launch_time_friendly = launch_time.strftime("%B %d %Y")
print("Server was launched at: ", launch_time_friendly)
How can I get the time the instances were created into a user friendly format?
There is both a datetime module and a datetime class. You are attempting to call the module:
import datetime
dt = datetime(2019, 3, 1) # This will break!
Instead, you need to either import the class from the module:
from datetime import datetime
dt = datetime(2019, 3, 1) # Okay!
... or import the module and reference the class:
import datetime
dt = datetime.datetime(2019, 3, 1) # Good!
I write unit-tests for web application and i should change function waiting time TIME_TO_WAIT to test some modules.
Example of code:
import time
from datetime import datetime as dt
def function_under_test():
TIME_TO_WAIT = 300
start_time = dt.now()
while True:
if (dt.now() - start_time).total_seconds() > TIME_TO_WAIT:
break
time.sleep(1)
I see a way to solve this problem with patch of datetime.timedelta.total_seconds(), but i don`t know, how do this correctly.
Thanks.
As I wrote in the comment - I would patch out dt and time in order to control the speed of of test execution like so:
from unittest import TestCase
from mock import patch
from datetime import datetime
from tested.module import function_under_test
class FunctionTester(TestCase):
#patch('tested.module.time')
#patch('tested.module.dt')
def test_info_query(self, datetime_mock, time_mock):
datetime_mock.now.side_effect = [
datetime(year=2000, month=1, day=1, hour=0, minute=0, second=0),
datetime(year=2000, month=1, day=1, hour=0, minute=5, second=0),
# this should be over the threshold
datetime(year=2000, month=1, day=1, hour=0, minute=5, second=1),
]
value = function_under_test()
# self.assertEquals(value, ??)
self.assertEqual(datetime_mock.now.call_count, 3)