time and datetime modules producing different result - python

Why gmt and utc results are different when running following code.
import time
import datetime
print( time.mktime(time.gmtime()))
print(datetime.datetime.utcnow().strftime("%s"))
Output:
1571984607.0
1571981007
I read many articles gmt and utc both will give same result. Why I am getting different result here.
gmt is 1 hour advance in time module when I converted it to IST.

Related

how do i get only the time in python without the date and year?

I need to get time in python and i am using time.ctime() and it returns this Thu Jul 8 15:37:26 2021
But i only need 15:37:26 and i cant figure out how to get only this and not the date and year.
I already tried using datetime where i could not figure it out either so im trying with time now.
here is a bit of code for the context:
cas = time.ctime()
cas = str(cas)
api.update_status('nyni je:'+ cas )
time.sleep(60)
Anyone know how to do it?
print(datetime.datetime.now().time().isoformat(timespec='seconds'))
import datetime
print(datetime.datetime.now().strftime("%H:%M:%S"))
imports
from datetime import datetime
code
now = datetime.now()
cas = now.strftime("%H:%M:%S")
print(cas)
You can use strftime to convert a datetime value to a string of a certain format. In your case you can use %H:%M:%S to only get the time. The same function can be used to get the date as well, you can read more here.
Take a look at the "strftime() and strptime() Format Codes" section also for how you can format it.

make python datetime include local time zone

I wrote this python code but I am facing problems to make it work properly at the level of time zone. So basically the datetime.now() is not working as expected as it is not compliant to my local time (Paris local time) . Any idea how to sovle this please.
from datetime import datetime, timedelta
from airflow.operators import
GoogleCloudStorageToGoogleCloudStorageOperator
copy_trm = GoogleCloudStorageToGoogleCloudStorageOperator(
task_id='copy_file',
source_bucket="source",
source_object="input-files/*.orc",
destination_bucket="destination",
destination_object="output-files/recent",
last_modified_time=datetime.now() - timedelta(days=1)
Best Regards
use pytz module
import pytz
tz = pytz.timezone('Pacific/Johnston') #change it to your suitable timezone
ct = datetime.now(tz=tz)
If you want to know your current timezone name. It is possible with below code:
import datetime
dt = datetime.datetime.now()
dt.astimezone().tzname()
Output:
'IST'
You can send time in UTC format as:
dt.astimezone().utcnow()
With the standard library, requires the numerical offset
If you have the numerical offset of your timezone (compared to UTC) then you use the standard library:
>>> from datetime import datetime, timezone
>>> datetime.now().strftime("%c (%Z)")
'Wed Feb 13 23:00:06 2019 ()'
>>> datetime.now(tz=timezone.utc).strftime("%c (%Z)")
'Wed Feb 13 22:00:11 2019 (UTC)'
>>> datetime.now(tz=timezone(timedelta(hours=2))).strftime("%c (%Z)")
'Thu Feb 14 00:00:20 2019 (UTC+02:00)'
Though since the offset can change throughout the year (e.g. with daylight saving time), it is recommended to use a named timezone.
With dateutils, using the host timezones database
The Python documentation on timezone points to the dateutil.tz package which will use the timezone database from the machine it runs on. The pytz package on the other hand comes with a bundled timezone database.
I would personally recommend the dateutil package since the database already exists on the running machine. As long as the machine is kept up-to-date (as any server and PC should) you are good to go.
>>> from dateutil.tz import gettz # GNU/Linux and macOS
>>> # Or, on Windows: from dateutil.tz.win import gettz
>>> datetime.now(tz=gettz("Europe/Paris")).strftime("%c (%Z)")
'Wed Feb 13 23:00:58 2019 (CET)'
>>> datetime.now(tz=gettz("Asia/Taipei")).strftime("%c (%Z)")
'Thu Feb 14 06:01:27 2019 (CST)'

Python date comparison with string output/format

I'm currently trying to writing a script to automate a function at work, but I'm not intimately familiar with Python. I'm trying to take a XML dump and compare a specific entry's date to see if the time has passed or not.
The date is in a particular format, given:
<3-letter Month> <DD> <HH:MM:SS> <YYYY> <3-letter Timezone>
For example:
May 14 20:11:20 2014 GMT
I've parsed out a string in that raw form, and need to somehow compare it with the current time to find out if the time has passed or not. That said, I'm having a bit of trouble figuring out how I should go about either formatting my text, or choosing the right mask/time format in Python.
I've been messing around with different variations of the same basic format:
if(trimmed < time.strftime("%x") ):
Trimmed is the clean date/time string. Time is derived from import time.
Is there a simple way to fix this or will I have to dig into converting the format etc.? I know the above attempt is simplistic, but I'm still very new to Python. Thanks for your time and patience!
You should use combination of gmtime (for GMT time),mktime and datetime.
from time import gmtime,mktime
from datetime import datetime
s = "May 14 20:11:20 2014 GMT"
f = "%b %d %H:%M:%S %Y GMT"
dt = datetime.strptime(s, f)
gmt = datetime.fromtimestamp(mktime(gmtime()))
if dt<gmt:
print(dt)
else:
print(gmt)

Python - if given GMT Offset, and Given UTC - How to get the current time in a time zone?

I am am given the following:
The offset of the user's time from GMT in minutes. For example, GMT+10 is
timezone_offset = 600.
I use pytz to get the current time in UTC:
from datetime import datetime
from pytz import timezone
now_utc = datetime.now(timezone('UTC'))
How do I the get the users time?
Thanks
You can add timedelta(hours=10) or timedelta(minutes=600) to the datetime object containing the UTC time.
However, it would be a better idea to store the timezone instead of the offset and then use Python's timezone functions to convert the time.

Using python datetime.datetime.strptime on windows with BST timezone

I need to parse many different dates in many different formats. I am having trouble with the following and wondered if anyopne could explain why;
The following works on a linux system:
from datetime import datetime
datetime.strptime('Tue 23 Aug 2011 09:00:07 PM BST','%a %d %b %Y %H:%M:%S %p %Z')
But running under windows it raises
ValueError: time data does not match format
However, if I try GMT not BST on windows, it works fine;
from datetime import datetime
datetime.strptime('Tue 23 Aug 2011 09:00:07 PM GMT','%a %d %b %Y %H:%M:%S %p %Z')
Is there a reason python does not understand the BST timezone under windows, but it works fine under Linux?
thanks,
Matt.
In my opinion, parsing a three-letter time zone code like this is not a good practice (unless of course you have no choice). For example, "EST" is commonly used in the USA for UTC-4/5 and is also commonly used in Australia. So any support for "EST" must therefore be dependent on locale. It would not surprise me if "BST" was similarly ambiguous.
I highly recommend using the pytz module in which British civil time is given the string identifier Europe/London and UTC is called Etc/UTC. The pytz API will give consistent results regardless of the locale of the user or system running the application.
If you are working on a UI that must be tied to locale, or parsing inputs with formats you cannot change, then consider using a dictionary of abbreviations to pytz timezone objects. For example: {'BST': 'Europe/London'}. Then your application can work with UTC dates and times uniformly, which will greatly reduce the possibility of errors.

Categories

Resources