#!/usr/bin/python
import os
import pathlib
import os.path
from datetime import datetime
i = datetime.now()
datess = i.strftime('%d')
months = ["Unknown",
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"]
now = (datetime.now())
year = (now.year)
print (year)
month = (months[now.month])
print(month)
# I want to print C:\apache-tomcat\store\retail_sector\sugar\Year.month/date
#The exact path is C:\apache-tomcat\store\retail_sector\sugar\2017.aug/24 but i want to print the year and date as varible
p = pathlib.Path('C:\apache-tomcat\store\retail_sector\sugar\2017.aug/24')
if p.is_dir():
print "Directory is created"
文件路径是C:\ apache-tomcat \ store \ retail_sector \ sugar \ 2017.aug / 24但我希望打印年份日期为可变,如C:\ apache-tomcat \ store \ retail_sector \ sugar \ Year.month /日期。请帮助我如何做到这一点。
答案 0 :(得分:1)
如果我理解你想要做什么,一种可能性是使用time.strftime
function,它允许您将日期转换为指定的格式:
import time
now = time.localtime()
date_string = time.strftime('%Y.%b/%d', now)
print(date_string)
这将打印
'2017.Aug/24'
'%Y.%b/%d'
部分指定格式,%Y
表示年份,%b
表示缩写的月份名称,%d
表示月份的日期。您可以在documentation中找到完整的可用格式列表。
然后,您可以使用date_string
构建路径:
path_string = '/my/test/path/%s' % date_string
print(path_string)
这将打印:
'/my/test/path/2017.Aug/24'
如果您希望月份为小写,则可以使用
path_string = '/my/test/path/%s' % date_string.lower()