How get a datetime string to suffix my filenames? - python

I need a function to generate datafile names with a suffix which must be the current date and time.
I want for the date Feb, 18 2014 15:02 something like this:
data_201402181502.txt
But this is that I get: data_2014218152.txt
My code...
import time
prefix_file = 'data'
tempus = time.localtime(time.time())
suffix = str(tempus.tm_year)+str(tempus.tm_mon)+str(tempus.tm_mday)+
str(tempus.tm_hour)+str(tempus.tm_min)
name_file = prefix_file + '_' + suffix + '.txt'

You can use time.strftime for this, which handles padding leading zeros e.g. on the month:
from time import strftime
name_file = "{0}_{1}.txt".format(prefix_file,
strftime("%Y%m%d%H%M"))
If you simply turn an integer to a string using str, it will not have the leading zero: str(2) == '2'. You can, however, specify this using the str.format syntax: "{0:02d}".format(2) == '02'.

Looks like you want
date.strftime(format)
The format string will allow you to control the output of strftime, try something like:
"%b-%d-%y"
From http://docs.python.org/2/library/datetime.html

Using str.format with datetime.datetime object:
>>> import datetime
>>> '{}_{:%Y%m%d%H%M}.txt'.format('filename', datetime.datetime.now())
'filename_201402182313.txt'

Related

Python formatted strings and datetime

Is this not allowed or did I type something wrong?
import datetime
print(f"Current Time: {datetime.datetime.now().strftime("%I:%M:%S %p")}"
Syntax error at %I:%M...
^
You are ending your fstring by using double quotes in your strftime() function, use single quotes or escape them.
For example:
print(f"Current Time: {datetime.datetime.now().strftime('%I:%M:%S %p')}"
Also, not related to your question, but you are not really using fstrings in the right way.
It would look a lot nicer if you defined a 'current time' variable and then put it in your fstring.
For example:
current_time = datetime.datetime.now().strftime('%I:%M:%S %p')
print(f"Current Time: { current_time }")
Why not like this:
from datetime import datetime
print(f'Current Time: {datetime.now():%I:%M:%S %p}')
See PEP498.
print(f'Current Time: {datetime.datetime.now().strftime("%I:%M:%S %p")}')
Quotes bro.
The datetime class already has a pre-configured date to string method : strftime()
So your code can look something like this :
import datetime
date_today = datetime.datetime.now()
date_today.strftime('%I:%M:%S %p')
Its because of quotes. Here is workaround method and your original method.
import datetime
print (f'Current Time : {datetime.datetime.now().strftime("%I:%M:%S %p")}')
import datetime
d = datetime.datetime.now().strftime("%I:%M:%S %p")
print(f"Current Time: {d}")

How to convert a downloaded string to datetime format?

I am trying to check if today's date < date downloaded from text file online. Here is my code :
import datetime
import requests
URL = "http://directlinktotextfile.com/text.txt"
result = requests.get(URL)
today = datetime.datetime.now().date()
Url_date = result.text
Url_date.strip()
Url_date = datetime.date(Url_date)
if today < Url_date :
print "Today is less than future date"
raw_input()
else:
print "Today is greater than or = to future date"
raw_input()
The result that comes back is just this : 2018,02,14. I use .strip() in case there might be blank spaces or extra lines. I've printed out result.text after strip() and it shows the correct details. Why is it that I can't check if today < Url_date. It works fine if I enter manually a date into datetime.date(2018,02,14), but when I'm downloading the string it won't work. Any suggestions?
You pass string to datetime.date() which should be each an integer.
Url_list = []
Url_list = Url_date.split(",")
yr = int(Url_list[0])
mn = int(Url_list[1])
d = int(Url_list[2])
Now pass these integers to datetime.date
Url_date = datetime.date(yr, mn, d)
The arguments you pass to datetime.date(arg1, arg2, arg3) are not strings as a whole. When you pass it from url, what you are actually doing is
datetime.date("2018,2,14")
Note that you are passing only one string argument and not 3 different integers. You should split the date string using comma and then convert each into integers and then pass them as arguments to datetime.date.
Here is what your code is trying to do :
Url_date = datetime.date("2018,02,14")
But he wants to have:
Url_date = datetime.date(2018,02,14)
Do
Url_date.split(',') # Result: ['2018','02','14']
And then convert all the string in the array in integers
It should be ok :)
Use strptime:
import datetime
today = datetime.datetime.now().date()
parsed = datetime.datetime.strptime("2018,02,14", "%Y,%m,%d").date()
print(today < parsed) # True

How to convert number to time in python?

I need convert number to time.
For example:
I need to convert 1230 to 12:30 or 0730 to 07:30.
How to convert a number to time in python?
We can create a function that takes a string and returns the time.
This can all be done in one line by slicing the string up to the minutes (done with [:2]) and then concatenating a ':' and finally concatenating the minutes with [2:].
def getTime(t):
return t[:2] + ':' + t[2:]
and some tests to show it works:
>>> getTime("1230")
'12:30'
>>> getTime("0730")
'07:30'
>>> getTime("1512")
'15:12'
Note how the function cannot take an integer and convert this to a string, as otherwise entries with leading zeros would fail. E.g. 0730 wouldn't work.
Yes, to answer #AbhishtaGatya, this could be written using a lambda function, but doing so wouldn't be advisable. However:
getTime = lambda t: t[:2] + ':' + t[2:]
works just the same as above.
You can insert ":" to the index 2
val = 1230
new= ([str(i) for i in str(val)])
new.insert(2,":")
print(''.join(new))
output:
12:30
Assuming the input is a string, you can do this:
number_str = '0730'
time_str = number_str[:2] + ':' + number_str[2:]
print(time_str) # Output: '07:30'
If you are sure that you only have 4 digits as strings one way is
new = '%s:%s'%(string[:2], string[2:])
Recommended is however to use the datetime handling within python
datetime.
from datetime import datetime
t1="1205"
t2="0605PM"
#%I - 12 hour format
print t1,(datetime.strptime(t1,"%I%M")).strftime("%I:%M")
print t2,(datetime.strptime(t2,"%I%M%p")).strftime("%I:%M")
#%H - 24 hour format
print t1,(datetime.strptime(t1,"%I%M")).strftime("%H:%M")
print t2,(datetime.strptime(t2,"%I%M%p")).strftime("%H:%M")
All of these require 4 digits for your time. This code will add a zero to the front if there are 3 digits. It will check for invalid times.
def conv_num_time(time):
num_str = ('{:04}'.format(time))
time_str = num_str[:2] + ':' + num_str[2:]
if int(num_str[:2])>23 or int(num_str[2:])>59:
print("Invalid time")
else:
print(time_str)
user_time = int(input(': '))
conv_num_time(user_time)

python strptime from UTC string to datetime regex re.sub

im using the following that works awesome for converting a UTC string to date times -- except when the milliseconds are LONGER than 6 digits. than it blows. urgh*&^*&
format = '%Y-%m-%dT%H:%M:%S'
if '.' in value:
format = format + '.%f'
if value.endswith('Z'):
format = format + 'Z'
return datetime.strptime(value, format)
here is the stacktrace
File "/usr/lib64/python2.6/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '2013-07-19T13:02:53.8241899Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'
whats a method to restrict the milliseconds to 6 digits in length. ive used using '{:%Y-%m-%dT%H:%M:%S.6%f}'.format( datetime ) but that helps nonce/
so trying re.sub( ) to limit the decimals (if any) following the '.'character in the provided string. but am not very regex savvy.
im using python 2.6.* on the machine.
Sounds like a job for dateutil.
$ pip install python-dateutil
$ python
>>> import dateutil.parser
>>> d = dateutil.parser.parse('2013-07-19T13:02:53.8241899Z')
>>> print d
2013-07-19 13:02:53.824189+00:00
You could use .partition() method to parse the string:
from datetime import datetime
sz = '2013-07-19T13:02:53.8241899Z' # utc time in rfc3339 format (without offset)
sz = sz.rstrip('Z') # remove ending 'Z' if present
timestr, _, digits = sz.partition('.')
utc_dt = datetime.strptime(timestr, '%Y-%m-%dT%H:%M:%S')
if digits:
microseconds = int(digits, 10) * 10**(6 - len(digits))
utc_dt = utc_dt.replace(microsecond=int(microseconds + .5))
If you want to use re.sub and don't mind truncating the microseconds:
import re
from datetime import datetime
sz = '2013-07-19T13:02:53.8241899Z'
if '.' in sz:
sz = re.sub(r'(\.\d{,6})\d*Z?$', r'\1Z', sz) # truncate to 6 digits +Z
else: # no fractions
sz = sz.rstrip('Z') + '.0Z'
utc_dt = datetime.strptime(sz, '%Y-%m-%dT%H:%M:%S.%fZ')
If you wanted to do it with re.sub, here's a short example of one way to do that.
import re
from datetime import datetime
value = '2013-07-19T13:02:53.8241899Z'
regex = r"(\d{6,}\d+)"
if re.search(regex, value):
repl = lambda x: x.group(0)[:6]
value = re.sub(pattern=regex, repl=repl, string=value)
format = '%Y-%m-%dT%H:%M:%S'
if '.' in value:
format = format + '.%f'
if value.endswith('Z'):
format = format + 'Z'
print datetime.strptime(value, format)

Add utc time to filename python

How can i get the current time in UTC time (Zulu style for hours and minutes: 0100Z) , and add it to a string so i can concatenate it
This gives me cannot concatenate string:
import datetime
utc_datetime = datetime.datetime.utcnow()
utc_datetime.strftime("%Y-%m-%d-%H%MZ") //Result: '2011-12-12-0939Z'
filename = '/SomeDirectory/AnotherDirectory/FilePrefix_'+utc_datetime+'.txt'
And this gives me another string for the filename:
//returns: /SomeDirectory/AnotherDirectory/FilePrefix_2011-12-12 09:42:15.374022.txt
import datetime
utc_datetime = datetime.datetime.utcnow()
utc_datetime.strftime("%Y-%m-%d-%H%MZ") //Result: '2011-12-12-0939Z'
filename = '/SomeDirectory/AnotherDirectory/FilePrefix_'+str(utc_datetime)+'.txt'
Thanks in advance
What you want to do is probably :
import datetime
utc_datetime = datetime.datetime.utcnow()
formated_string = utc_datetime.strftime("%Y-%m-%d-%H%MZ") //Result: '2011-12-12-0939Z'
filename = '/SomeDirectory/AnotherDirectory/FilePrefix_%s.txt'% formated_string
or in a one-liner way :
filename = '/SomeDirectory/AnotherDirectory/FilePrefix_%s.txt'%datetime.datetime.utcnow().strftime("%Y-%m-%d-%H%MZ")
When using datetime.strftime it returns the string formatted as you need, it does not modify the datetime object.
EDIT : use %s instead of +, thanks Danilo Bargen
The strftime method of a datetime object only returns a value, but doesn't manipulate the original object. You need to save the result into the variable itself, or into a new variable.
import datetime
utc_datetime = datetime.datetime.utcnow().strftime("%Y-%m-%d-%H%MZ")
utc_datetime //Result: '2011-12-12-0939Z'
Additionally, you shouldn't use + to concatenate several strings because of performance reasons. Use this instead:
filename = '/directory/prefix_%s.txt' % utc_datetime
You need to save the result of utc_datetime.strftime() into a variable:
>>> import datetime
>>> utc_datetime = datetime.datetime.utcnow()
>>> s=utc_datetime.strftime("%Y-%m-%d-%H%MZ")
>>> filename = '/SomeDirectory/AnotherDirectory/FilePrefix_' + s + '.txt'
>>> print filename
/SomeDirectory/AnotherDirectory/FilePrefix_2011-12-12-0946Z.txt
>>>
You're currently computing a value and throwing away the string result.

Categories