Write date and variable to file - python-3.x

I am trying to write a variable and the date and time on the same line to a file, which will simulate a log file.
Example: July 25 2018 6:00 pm - Variable contents here
So far I am able to write the variable to the file but I am unsure how to use the datetime library or other similar libraries. Some guidance would be appreciated.
Below is the current script.
import subprocess
import datetime
var = "test"
with open('auditlog.txt', 'a') as logfile:
logfile.write(var + "\n")

The fastest way I found is doing something like this:
import time
var = time.asctime()
print(var)
Result: Thu Jul 26 00:46:04 2018
If you want to change the placements of y/m/d etc. you can alternatively use this:
import time
var = time.strftime("%B %d %Y %H:%M pm", time.localtime())
print(var)
Result: July 26 2018 00:50 pm
Have a look here.
By the way, is the subprocess intended in your code? You don't need it to open/write to files. Also you should do logfile.close() in your code after you wrote to it.

Related

How can I parse a custom string as a timezone aware datetime?

How can I parse
18 January 2022, 14:50 GMT-5
as a timezone aware datetime.
pytz.timezone('GMT-5')
fails.
It appears I may need to parse the GMT part, and manually apply the 5 hours offset post parsing?
Hmm How about maybe:
import re
import datetime
foo = "18 January 2022, 14:50 GMT-5"
bar = re.sub(r"[+-]\d+$", lambda m: "{:05d}".format(100 * int(m.group())), foo)
print(datetime.datetime.strptime(bar, "%d %B %Y, %H:%M %Z%z" ))
I think that gives you:
2022-01-18 14:50:00-05:00

How to determine the appropriate the timezone to apply for historical dates in a give region in python3

I'm using python3 on Ubuntu 20.04.
I have a trove of files with naive datetime strings in them, dating back more than 20 years. I know that all of these datetimes are in the Pacific Timezone. I would like to convert them all to UTC datetimes.
However, whether they are relative to PDT or PST is a bigger question. Since when PDT/PST changes has changed over the last 20 years, it's not just a matter of doing a simple date/month threshold to figure out whether to apply the pdt or pst timezone. Is there an elegant way to make this determination and apply it?
Note upfront, for Python 3.9+: use zoneinfo from the standard library, no need anymore for a third party library. Example.
Here's what you can to do set the timezone and convert to UTC. dateutil will take DST changes from the IANA database.
from datetime import datetime
import dateutil
datestrings = ['1991-04-06T00:00:00', # PST
'1991-04-07T04:00:00', # PDT
'1999-10-30T00:00:00', # PDT
'1999-10-31T02:01:00', # PST
'2012-03-11T00:00:00', # PST
'2012-03-11T02:00:00'] # PDT
# to naive datetime objects
dateobj = [datetime.fromisoformat(s) for s in datestrings]
# set timezone:
tz_pacific = dateutil.tz.gettz('US/Pacific')
dtaware = [d.replace(tzinfo=tz_pacific) for d in dateobj]
# with pytz use localize() instead of replace
# check if has DST:
# for d in dtaware: print(d.dst())
# 0:00:00
# 1:00:00
# 1:00:00
# 0:00:00
# 0:00:00
# 1:00:00
# convert to UTC:
dtutc = [d.astimezone(dateutil.tz.UTC) for d in dtaware]
# check output
# for d in dtutc: print(d.isoformat())
# 1991-04-06T08:00:00+00:00
# 1991-04-07T11:00:00+00:00
# 1999-10-30T07:00:00+00:00
# 1999-10-31T10:01:00+00:00
# 2012-03-11T08:00:00+00:00
# 2012-03-11T09:00:00+00:00
Now if you'd like to be absolutely sure that DST (PDT vs. PST) is set correctly, you'd have to setup test cases and verify against IANA I guess...

Momentjs get time in current location

I'm trying to generate a momentjs object of a certain timestamp in the current day of a specified location. For example:
const timeNow = moment().tz('Africa/Cairo')
const startTime = moment('10:00 am', 'HH:mm a')
const endTime = moment('2:30 pm', 'HH:mm a')
Printing the above 3 variables outputs this:
Fri, 12:31 am
Thu, 10:00 am
Thu, 02:30 pm
Where the first result is in fact the current time in Cairo, However the other two results are the day before. How can I change it so that they return the current day?
You can simply do:
moment.tz('Africa/Cairo') // <= Moment Object
One small info: whenever you'll get to see some javascript date in a browser that will be shown in your system's time-zone. As javascript Date is UTC, browsers will show accordingly. Use moment.format() to get string values.

Format the time from moment js

When I am trying to receive mail from gmail, I get time in this format (Mon, 12 Jun 2017 10:29:07 +0530). I want to calculate time minus current time. How to do so?
var testDate = moment("Mon, 12 Jun 2017 10:29:07 +0530");
//Relative to time in human readble format
testDate.fromNow(); //3 days ago
You can simply call the moment constructor with the given Date format. moment.js is smart enough to parse it for you. To get the difference you can convert it into unix based time format and subtract it.
const givenTime = moment("Mon, 12 Jun 2017 10:29:07 +0530").unix()
const currentTime = moment().unix()
//Difference in milliseconds
const diff = givenTime - currentTime

momentjs wrong date returned

Im using momentjs in nodejs app and trying to parse timestamp string with momentjs to compare two dates. My code is:
moment('11/04/2016 01:00:00', 'DD/MM/YYYY HH:mm:ss')
and the output is:
{ _date: Fri Nov 04 2016 00:00:00 GMT+0000 (GMT Standard Time) }
But with the given format im expecting the return date to be Sun Apr 10 2016.
Seems like the format option is not working or im missing something
It works for me (moment version: 2.12.0)
var moment = require('moment')
var m = moment('11/04/2016 01:00:00', 'DD/MM/YYYY HH:mm:ss')
console.log(m.format('LLL')) // April 11, 2016 1:00 AM
Also changing days with months in both arguments works:
var m = moment('04/11/2016 01:00:00', 'MM/DD/YYYY HH:mm:ss') // same date as above
What version of moment are you using and how did you import it? How did you generate the output date? Is it just console.log?
(this should be a comment, but I wanted to add the code snippet)
Here's a sample code to return a string in your output format
var moment = require('moment');
var now = moment();
var date = moment('11/04/2016 01:00:00', 'DD/MM/YYYY HH:mm:ss');
console.log(now.format('ddd MMM D YYYY'));
console.log(date.format('ddd MMM D YYYY'));
Sorry it was my mistake. I've installed momentjs which is not the official moment package. After installing the moment package instead momentjs all is working as expected.

Resources